470,848 Members | 1,858 Online

# Numerical value of string

Hi all,

I am trying to find the numerical value of a string that stores a two digit number. I have found the numerical value of a char as:

char character;
cin >> character;
int number = character - 48; // Computing the numberical value of character entered
cout << "The number you entered is: " << number << endl << endl;

How do I do the same and find the numerical value of a string storing 2 digits? I know a way to do this using character arrays:
for (; *str != '\0' && *str >= '0' && *str <='9'; str++)
num = (num * 10) + (*str - '0');

But, I am not supposed to use if statements, character arrays, apstrings, or atoi in this program.

I am stumped. Any ideas?

Thanks,
Farah.
Oct 13 '06 #1
2 3435
Hi all,

I am trying to find the numerical value of a string that stores a two digit number. I have found the numerical value of a char as:

char character;
cin >> character;
int number = character - 48; // Computing the numberical value of character entered
cout << "The number you entered is: " << number << endl << endl;

How do I do the same and find the numerical value of a string storing 2 digits? I know a way to do this using character arrays:
for (; *str != '\0' && *str >= '0' && *str <='9'; str++)
num = (num * 10) + (*str - '0');

But, I am not supposed to use if statements, character arrays, apstrings, or atoi in this program.

I am stumped. Any ideas?

Thanks,
Farah.
Here is a sugestion:

std::string s ="48";
int n;

std::stringstream ss(s);
ss >> n;
Oct 13 '06 #2
D_C
293 100+
Expand|Select|Wrap|Line Numbers
1. result = 0;
2. cin >> ch;
3. while(character is a digit)
4. {
5.   result *= 10;
6.   result += ch - '0';
7.
8.   cin >> ch;
9. }
Oct 13 '06 #3