Splitting numbers

closed account (ETA9216C)
I have the concept of the code that i'm doing. Which is having the number example:1234 returned as 1 2 3 4 by finding the length of the number and using that length to set as a limit to have the number returned by diving by pow(10,length). My c++ is not that advance as of yet, so i've come to ask for help.

so this is my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <math.h>
using namespace std;

int main()
{
    int n,x,s,i,t;

    cout<<"Enter a value: ";
    cin>>n;



    for(x=1;x>=n;x++)
    {
        s=n/10;


           for(i=1;i<=s;i++)
            {

            n%=10;
            n/10;
            cout<<"Digit "<< i <<" = "<<n<<endl;
            s--;

            }

    }
    return 0;
}
 
s=n/10;


Be wary of division by integer issues.

Have you considered reading in as a string?
http://www.cplusplus.com/reference/string/string/

and then convert to numbers as needed?

OR read in as a number, and use
http://en.cppreference.com/w/cpp/string/basic_string/to_string

to get the "length" of the number
Just use % and / interchangeably.

1
2
3
4
5
6
7
8
9
10
11
string s;
cin>>n;

do
{
    s = atoi(n%10) + s;
    
} while(n/=10)

cout << s;
closed account (ETA9216C)
Can i have a brief explanation of what this

 
s = atoi(n%10) + s;


does?
@elohssa: Sorry, but your code won't do it.

If reading the number to be inspected as a string, as mutexe suggest, you simply may split it by reading it digit by digit from the string. No more computation is needed.

Otherwise when reading it f.e. as an unsigned integer you'll indeed use % and / operators. A really beautiful way may be a simple recursive function. Think about it!
Topic archived. No new replies allowed.