1
string test;
test="3527523";
int a=test[3];
std::cout<<a<<std::endl;

I was expecting output to be number 7, but I got 55 instead. I have searched through different posts, they all used this method without any problems.. I just don't know where the problem is in my case. Thank you for your help!

5 Answers5

6

test[3] returns char, which you're converting to an integer, so it returns the ASCII value of the character. 3 in ASCII is 55.

Try using char instead as the type of a:

char a = test[3];

std::cout << a; // 3

If you wanted the result to be an integer, subtract the character from '0':

std::string test = "3527523";

int a = test[3] - '0';

std::cout << a; // 3
David G
  • 94,763
  • 41
  • 167
  • 253
  • Thanks a lot for the help. I know I asked a really stupid question So what does '0' really do in here to make it a correct ans? – user2341380 May 11 '13 at 00:19
  • user2341380, If you consult a table of ASCII values, the values for `'0'`, `'1'`, `'2'`, `'3'`, `'4'`... are 48, 49, 50, 51... so when you subtract 51 (`'3'`) from 48 (`'0'`) you get 3. Works for all ASCII digits. – Patashu May 11 '13 at 00:23
  • `'0'` is a character literal and has the ASCII value of 48. When arithmetic is applied to at least one operand of type `char`, integral promotion is applied. That means `'0'` is converted to 48. The values of the characters from `'0'` to `'9'` are 48 to 53 (do you get it now) :)? – David G May 11 '13 at 00:23
  • @user2341380 Let's say we wanted to convert the character `'1'` to an integer. `'1'` has the ASCII value `49`. Subtracting from `'0'` (48) gives the integer `1` (49 - 48 == 0). – David G May 11 '13 at 00:25
  • @user2341380 Sorry, I meant (49 - 48 == 1). – David G May 11 '13 at 00:32
0

You get the char '7' by the brackets, which has the ASCII code 55 (48+7).

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0

Problem is that you assign test[3] to a variable of type int, thus causing the actual character code (55) to be printed instead of the represented character ('7'). Replace int with char or static_cast before printing.

Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
0

You don't "cast", you "convert".

You can use sscanf(), atoi() among other functions to convert the value of a string:

int iret = sscanf (test, "%d", &a);

The value of test[3] is the ASCII character '7', which is actually the integer "55".

PS: The beauty of "sscanf()" is that you can easily detect if a parse error occurred by checking for "iret != 1".

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Use atoi:

int atoi (const char * str); //Convert string to integer

For example:

string test;
test="3527523";
const char c = test[3];
int a=atoi(&c);
std::cout<<a<<std::endl;
TelKitty
  • 3,146
  • 3
  • 18
  • 21