我正在尝试从具有std::string
作为键的无序映射中接收值,其中一些字符串仅包含一个字符。我所有的输入都来自std::stringstream
我从中获取每个值并将其转换为字符,然后使用将其转换为字符串,根据文档和此答案
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
}