xor xor - 1 month ago 10
C++ Question

Having problems getting the ith character in a string

I want to access the

ith
char
in
str


int main() {
string str = "5.9x^11+x^3–3x^10";
for(int i = 0; i<17; i++){
cout<<i<<": ";
cout<<str.at(i)<<endl;
}
return 0;
}


what I expect:

0: 5
1: .
2: 9
3: x
4: ^
5: 1
6: 1
7: +
8: x
9: ^
10: 3
11: -
12: 3
13: x
14: ^
15: 1
16: 0


what I get:

0: 5
1: .
2: 9
3: x
4: ^
5: 1
6: 1
7: +
8: x
9: ^
10: 3
11: \342
12: \200
13: \223
14: 3
15: x
16: ^


I don't understand why the values at
11-13
aren't
-,3,x
respectively.

Answer

The character at position 11 is not the Unicode character U+002D MINUS, like you are expecting. It's actually the Unicode character U+2013 EN DASH. In UTF-8, U+2013 is encoded as the byte sequence 0xE2 0x80 0x93 (\342 \200 \223 in octal).

This typically happens when one uses a dumb word processor to write code, and auto-correct is enabled. That would be my guess as to what happened here.