Split numbers of an int. C ++

1

Hello! I'm reading and studying C ++ in the book "C ++ How to Program 5th Edition". There is a question on pg 97. Question 2.28 which I can not perform, it being:

Write a program that inserts a five-digit integer, separates the integer into its individual digits, and prints the separated digits each other by three spaces each. [Hint: Use integer and module division operators.] For example, if the user types 42339, the program should print: 4 2 3 3 9.

From what I understood, I must do:

#include <iostream>
using namespace std;

int main () {

int x ;
cin >> x; // Digitar cinco números

// eu não faço ideia como separar estes números?
// alguém pede me ajudar? 
return 0;
}
    
asked by anonymous 22.01.2017 / 19:05

1 answer

3

In your own text you have:

  

"Tip: Use integer division operators and module .

That's really the tip. Suppose you read the integer 42339 , as you yourself illustrate.

If you divide it by 10, how much?

42339 / 10 = 4233,9

Notice how the comma separates the first digit to the right (not by chance, ten) from its original number. In C ++, you can get these values by doing:

#include <iostream>
using namespace std;

int main() {

    int num = 42339;

    int dig = num % 10; // módulo (resto da divisão) por 10
    int sobra = int(num / 10); // divisão inteira por 10

    cout << "num: " << num << " dig: " << dig << " sobra: " << sobra << endl;

    return 0;
}

The result is this (see working on Ideone ):

num: 42339 dig: 9 sobra: 4233

In other words, to make one step of what you need, just apply this rule (use the module - that is, rest of the division - for 10 to get the digit, and the whole division to keep what is left over). Then repeat this procedure for the remaining steps until your entire division result is 0 (there is nothing left and you have processed all the digits).

    
22.01.2017 / 19:33