Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ converting char variable to string variable is returning ASCII value

Tags:

c++

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".

like image 587
nhershy Avatar asked Dec 04 '25 18:12

nhershy


2 Answers

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);
like image 130
R Sahu Avatar answered Dec 06 '25 08:12

R Sahu


You can also use alternative string constructor like this:

  ...
    else
    {
        return std::string(&c, 1);
    }
like image 31
Killzone Kid Avatar answered Dec 06 '25 09:12

Killzone Kid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!