468,457 Members | 1,631 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,457 developers. It's quick & easy.

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 3341
Suomi
2
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

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by dont bother | last post: by
5 posts views Thread by Marc Scheuner [MVP ADSI] | last post: by
16 posts views Thread by Martin Jørgensen | last post: by
2 posts views Thread by Ian Eagland | last post: by
2 posts views Thread by jediknight | last post: by
8 posts views Thread by farah727rash | last post: by
14 posts views Thread by Aman JIANG | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.