为什么这个字符作为整数放入向量中?
Why is this character put into the vector as an integer?
我正在尝试将一个字符放入堆栈,但它放入的是该字符的 ASCII 整数值。是什么原因造成的?我怎样才能将实际角色放入堆栈?
下面是一些简单的代码来说明我的意思:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> v;
std::string s = "ABCDEF";
char c = s[0];
v.push_back(std::to_string(c));
std::cout << v[0] << std::endl;
}
std::to_string
没有来自 char
的转换,但它确实有来自 int
的转换。因此 c
将隐式转换为具有相应 ASCII 值的 int
,而 this 将转换为 std::string
.
如果你想push_back
字符c
作为std::string
,你可以这样做:
v.push_back({c});
这是一个 demo。
我正在尝试将一个字符放入堆栈,但它放入的是该字符的 ASCII 整数值。是什么原因造成的?我怎样才能将实际角色放入堆栈?
下面是一些简单的代码来说明我的意思:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> v;
std::string s = "ABCDEF";
char c = s[0];
v.push_back(std::to_string(c));
std::cout << v[0] << std::endl;
}
std::to_string
没有来自 char
的转换,但它确实有来自 int
的转换。因此 c
将隐式转换为具有相应 ASCII 值的 int
,而 this 将转换为 std::string
.
如果你想push_back
字符c
作为std::string
,你可以这样做:
v.push_back({c});
这是一个 demo。