将单个字符转换为 std::string 前缀 \x01
Converting a single char to std::string prepends x01
我正在尝试从具有std::string
键的无序映射中接收值,其中一些字符串仅包含一个字符。我所有的输入都来自一个std::stringstream
,我从中获取每个值并将其转换为 char,然后使用std::string result {1, character};
将其
转换为字符串,根据文档和这个答案,这似乎是有效的。
但是,当我这样做时,字符串会得到一个 \x01 前缀(对应于值 1(。这使得在映射中找不到字符串。我的调试器还确认字符串的大小为 2,值为"\x01H"。
为什么会发生这种情况,我该如何解决?
#include <iostream>
#include <sstream>
#include <unordered_map>
int main()
{
const std::unordered_map<std::string, int> map = { {"H", 1}, {"BX", 2} };
std::stringstream temp {"Hello world!"};
char character = static_cast<char>(temp.get()); // character is 'H'
std::string result {1, character}; // string contains "x01H"
std::cout << result << " has length " << result.size() << std::endl; // H has length 2
std::cout << map.at(result) << std::endl; // unordered_map::at: key not found
}
与您链接到的问题不同,您使用的是大括号{}
,而不是括号()
。这使它成为初始值设定项列表,而不是您期望的构造函数。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 编译器如何在前缀和 postix 运算符之间进行区分?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 将单个字符转换为 std::string 前缀 \x01