user2341380
user2341380

Reputation: 15

wrong result of casting string to int C++

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!

Upvotes: 1

Views: 2225

Answers (5)

TelKitty
TelKitty

Reputation: 3156

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;

Upvotes: 0

paulsm4
paulsm4

Reputation: 121599

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".

Upvotes: 0

Stefano Sanfilippo
Stefano Sanfilippo

Reputation: 33046

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.

Upvotes: 0

David G
David G

Reputation: 96790

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

Upvotes: 6

Joop Eggen
Joop Eggen

Reputation: 109532

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

Upvotes: 0

Related Questions