Justin T.
Justin T.

Reputation: 149

C++ Printing an integer derived from a string's character

I'd like to print the very first number. For some reason, its printing out as 49 instead of 1...

 int n = 111111251;
 string s = to_string(n);
 int num = s[0];
 cout << num << endl;

Upvotes: 0

Views: 849

Answers (3)

user2249683
user2249683

Reputation:

While doing the right thing converting an integer to a string you change the type of the first element in the string from 'char' to 'int'. That effects the output: The character representation is still '1', but the numerical value is (ASCII) 49 (Have a look at http://en.wikipedia.org/wiki/ASCII).

You probably want char character = s[0]; cout << character << endl; or int num = s[0]; cout << char(num) << endl;

Upvotes: 0

dwcanillas
dwcanillas

Reputation: 3651

Its printing out 49 because that is the ascii value of 1.

If you want to print out the character, just print out s[0] directly, or convert it back to an int properly. Consider the following code:

int main()
{
    int n = 111111251;
    string s = to_string(n);
    cout << s[0] << endl;

    int num = s[0];
    cout << num << endl;

    int num2 = s[0] - '0';
    cout << num2 << endl;

    return 0;
}

This prints out:

1
49
1

Upvotes: 2

Shay Gold
Shay Gold

Reputation: 403

49 is the ASCII value of 1.

Hope I helped,

Upvotes: -1

Related Questions