将char变量转换为字符串变量的C ++返回ASCII值

时间:2017-10-23 20:44:35

标签: c++

我的功能如下:

string toOriginal(char c)
{
    if (c == '$')
        return "car";
    else if (c == '#')
        return "cdr";
    else if (c == '@')
        return "cons";
    else
    {
        string t = to_string(c);
        return t;
    }
}

然而,当我的角色c包含类似' r'的值时,我希望它能够返回" r"作为一个字符串。但是,它返回一个字符串" 114"。

3 个答案:

答案 0 :(得分:5)

std::to_string does not have an overload that takes a char. It converts the char to an int and gives you the string representation of the int.

Use std::string's constructor.

string t(1, c);

答案 1 :(得分:2)

你也可以使用这样的替代字符串构造函数:

  ...
    else
    {
        return std::string(&c, 1);
    }

答案 2 :(得分:1)

The method to_string() is for converting a numerical value to a string. A char is a numerical type.

See this related question on how to do it right: Preferred conversion from char (not char*) to std::string