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

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Your arguments need to be switched: e.g. string t(1, c); Other than that, it worked. Thanks.
@nhershy, aah. Yes.
2

You can also use alternative string constructor like this:

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.