string at

If I declare a string:
 
string s = "bob";


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.

So what does the .at() do exactly? Thank you.
It is the same thing. A char is an integer value.

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>
using namespace std;

int main()
  {
  char x, y;

  x = 65;
  y = 'A';

  cout << x << endl;
  cout << y << endl;

  return 0;
  }

Hope this helps.
Cool. So if I do

int z = s.at(0);

z would be set to the ASCII code of 'b', right?

but if I do

char z = s.at(0);

z would be set to 'b', right?

Thank you.
They would both be the same. If you want to, think of char as an integer with a limited range. (0-255)
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>
using namespace std;

int main() {
    // ch, i, and us all have the same value : 98
    char ch = 98;
    int  i  = 'b';
    unsigned short 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;
}
Last edited on
Topic archived. No new replies allowed.