将单个字符转换为 std::string 前缀 \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
}

与您链接到的问题不同,您使用的是大括号{},而不是括号()。这使它成为初始值设定项列表,而不是您期望的构造函数。

最新更新