0

I have to get a string of numbers of 2 digits separated by spaces, take the numbers out somehow and do operations with them. But the values are all going wrong, see for yourselves:

... string = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08"; //example for (int i = 0; i < string.size()-2; i += 3){ arr[i] = 10 * string[i] + string[i+1]; cout << arr[i] <<' '<< 10 * string[i] <<' '<< string[i] << string[i+1] <<endl; } 

output: 536 480 08 i guess 0 times 10 isn't 480 as well as that plus 8 equals 536 530 480 02 550 500 22 625 570 97 566 510 38 543 490 15 528 480 00 568 520 40 528 480 00 603 550 75 532 480 04 533 480 05 535 480 07 606 550 78 580 530 52 540 490 12 578 530 50 605 550 77 619 570 91 536 480 08 
1
  • 1
    What is arr? Are you trying to do math on ascii character values? Commented Feb 25, 2014 at 1:00

4 Answers 4

2

You're doing your calculation with the ASCII values of the characters, not the numeric values of the digits. E.g. '0' is 48, '1' is 49, and so on.

for (int i = 0; i < string.size()-2; i += 3){ arr[i] = 10 * (string[i]-'0') + (string[i+1]-'0'); cout << arr[i] <<' '<< 10 * string[i] <<' '<< string[i] << string[i+1] <<endl; } 
Sign up to request clarification or add additional context in comments.

Comments

1

You're misunderstanding the int values you're retrieving. Just as an example, the 08 you're pulling.

'0' is not 0, it's 48
'8' is not 8, it's 56

48 * 10 + 56 = 536 

instead of taking the ASCII representation of a character and using that in your calculations, use atoi.

Also, instead of going char by char you might want to look into the many ways to split a string of text in C++.

Comments

0

Converting a character to an integer gives you the numeric value that represents the character; for the numeric digits, that's not the same as the value of the digit. Just about every computer you'll find these days uses ASCII coding, where '0' is represented by the value 48, '1' by 49, and so on.

You want to subtract the value that represents '0' so that '0' becomes 0, '1' becomes 1, and so on:

arr[i] = 10 * (string[i] - '0') + (string[i+1] - '0'); 

Comments

-1

You could use the stoi()(string to integer) to convert your string to numerical values and then perform your operations.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.