I need a way to get a number from the user, break that number up (eg. 1128 into 1 1 2 and 8), and then manipulate each number. Here is what I tried to do, failed horribly:

#include <iostream>
#include <string>
#include <cmath>
int main()
     string str;
     int a = 0;
     cout << "Number: " << endl;
     cin >> str;
     for(int i = 0,i2 = 1; i < str.length(); i++, i2++)
          int x = pow(16.0, i);
          int y = str[i2];
          cout << y << ", ";
          cout << x << ", ";
          a += (h_str[h_str.length() -i2]) *x;
          cout << a << endl;
     cout << sum << endl;         
10 Years
Discussion Span
Last Post by hinduengg

>>int y = str[i2];

str[i2] contains the ascii value of the character, such as '1' is ascii value 49. See this ascii chart for all of them. To convert it to decimal just subtract '0' int y = str[i2] - '0'; >>a += (h_str[h_str.length() -i2]) *x;
I have no idea what that is supposed to do. where is h_str declared ?


i was changing it to make sense here, in my program they're all h_str instead of just str.

Thanks for your help going to try it out now


Why all this? You wanted to input a number from the user and manipulate each digit.

But what do you want to do with the digits????
Because I know a way to get each digit separately.


Suppose you input the number as 12.Then you can seperate them by


int main()
  int i,r,num;
  cout<<"Enter number: ";

       r = num% 10;
       i = num/10;


r = num % 10;
Suppose you input 12, 'r' gets the value 2. Then when the loop runs the second time 'r' gets 1. Then the loop stops. I think this is a better way.


These kinds of problems are all basically the same... they involve integer division and modulo operations..

In other words 1128 / 10 = 112, and 1128 % 10 = 8. 112 / 10 = 2, etc..
You can see where I'm going with this yeah?

A nice twist on this problem is the famous "reverse digits" problem.. there are many ways to do it, but it's basically all the same.


if n=1128(int type)
use this-

  digit=n%10;    //extract individual digit to use 
  cout<<digit<<endl   //or do any operation on it
  n=n/10;   //reducing the n by 10 so that it finally turns to    (0.something)

I hope it works:)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.