2

My function looks like this:

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;
    }
}

However, when my character c contains a value like 'r', I would like for it to return "r" as a string. However, it returns a string "114".

nhershy
  • 643
  • 1
  • 6
  • 20

3 Answers3

7

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);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

You can also use alternative string constructor like this:

  ...
    else
    {
        return std::string(&c, 1);
    }
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37
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

ypnos
  • 50,202
  • 14
  • 95
  • 141