Connecting Tech Pros Worldwide Help | Site Map

Numerical value of string

Newbie
 
Join Date: Oct 2006
Posts: 3
#1: Oct 13 '06
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.
Newbie
 
Join Date: Oct 2006
Posts: 2
#2: Oct 13 '06

re: Numerical value of string


Quote:

Originally Posted by farah727rash

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;
D_C D_C is offline
Needs Regular Fix
 
Join Date: Jun 2006
Posts: 294
#3: Oct 13 '06

re: Numerical value of string


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. }
Reply