Get number in string in C++

Hello,
I enter 30 and I expected output be 0 15 but I have 240 255.
I think program multiple asci code with 5 but I want to multiply 0 * 5 and 3 * 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
int main()
{

	cout << "Number??? " << endl;;
	string str;
	int sum = 0;
	int j = 0;
	getline(cin, str);
	for (int i = str.length() -1; i >=0 ; i--)
	{
		//sum += pow(8,j++)*str[i];
		cout << str[i] * 5 << " ";
	}
	//cout << sum;
	

}
str[i] for 30 is ascii '0' and ascii '3' which are NOT 3 nor 0.
you can adjust this:
cout << (str[i] - '0')*5
the digits 0-9 are in order in the ascii table so this normalizes their ascii values to the related numeric value. 0 is the null / end of string, and 1-20 or so are weird stuff for old serial port comms and other such odd non printable characters :)
Last edited on
My problem has been solved but could you please more explain why we use -->> - '0' ?

I didn't understand and why str[0] and str[1] aren't getting us 0 and 3?

I'm confused
Last edited on
http://www.asciitable.com/

All mainstream modern systems encode chars using ASCII. Chars are a type of integer.
The value of '3' as a char is 51.
The value of '0' as a char is 48.
When you do '3' - '0', you get 51 - 48, which is the actual integer value of 3.

It's basically the cheapest way to convert a one-digit 0-9 char to its equivalent integer.
Last edited on
All mainstream modern systems encode chars using ASCII. -- well, actually, most use unicode these days. But that is another can of worms best not gone into here.

str[i] for 30 is ascii '0' and ascii '3' which are NOT 3 nor 0. ^^^ what he said is another way of saying what I said, to explain it deeper. The first (more than 10) characters in the ascii encoding were reserved for special codes so they were unable to use those for one to one mappings of the digits. One might also ask why there are symbols between 'Z' and 'a' instead of A-Z followed by a-z. The only answer I can give you is 'that is how they did it'. The number-to-symbol encoding is largely arbitrary, but I suspect some madness in their methods that let you do nifty hex or binary magic on the table if you look for patterns in the bits (something that was worth doing when the table was made due to the incredible slowness of computers at that time in history). If you noticed, 48 is a hex power of 10 (30) so the numeric codes are 30, 31, 32, ... 39 but they are a bit nonsensical in base 10.
Last edited on
Topic archived. No new replies allowed.