Does s.at(0) give me the character 'b' or the ASCII code of 'b'?
I checked the .at() function for string on cplusplus.com and the website says it should give the character at that position, but my professor told me it gives me the ASCII code.
When you cout << mychar, the integer value of mychar is treated specially and you see a pretty picture of the character represented by the ASCII value.
Try the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
usingnamespace std;
int main()
{
char x, y;
x = 65;
y = 'A';
cout << x << endl;
cout << y << endl;
return 0;
}
ostreams, like cout, displays 'b' if you provide it with a char with value 98, but the value if it's any other integral type.
But can use casting to control this behviour.
Andy
char : b = 98
int : b = 98
ushort : b = 98
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
usingnamespace std;
int main() {
// ch, i, and us all have the same value : 98
char ch = 98;
int i = 'b';
unsignedshort us = ch;
// but cout knows we want to see 'b' when we write out a char with value 98
// whereas we want the value in other cases.
cout << "char : " << ch << " = " << static_cast<int>(ch) << endl;
cout << "int : " << static_cast<char>(i) << " = " << i << endl;
cout << "ushort : " << static_cast<char>(us) << " = " << us << endl;
return 0;
}