By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
449,033 Members | 1,020 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 449,033 IT Pros & Developers. It's quick & easy.

Numerical value of string

P: 3
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
Share this Question
Share on Google+
2 Replies


P: 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

100+
P: 293
D_C
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.