【问题标题】:Converting a single char to std::string prepends \x01将单个字符转换为 std::string 前置 \x01
【发布时间】:2023-03-19 18:25:02
【问题描述】:

我正在尝试从以std::string 作为键的无序映射接收值,其中一些字符串仅包含一个字符。我所有的输入都来自std::stringstream,我从中获取每个值并将其转换为字符,然后使用
std::string result {1, character}; 将其转换为字符串,根据documentationthis answer.

但是,当我这样做时,字符串会在前面加上 \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
}

【问题讨论】:

    标签: c++ string std c++17 sstream


    【解决方案1】:

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

    【讨论】:

    • 啊,这么简单的错误。感谢您的帮助!
    • @melpomene 完全正确。
    • 又是另一个为什么不应该使用统一初始化的例子......坚持使用括号,这更明确;我个人甚至在初始化列表中使用括号:std::string s({'a', 'b', 'c'})。 (承认,尝试显式调用默认构造函数实际上是声明一个函数存在问题,但该规则远没有那么复杂......)。
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2016-01-28
    • 2019-03-31
    • 2019-05-29
    相关资源
    最近更新 更多