Split numbers of an int. C++

Asked

Viewed 2,948 times

1

Hello! I am reading and studying about C++ in the book " C++ How to Program 5th edition ". There is a question in pg 97. Question 2.28 which I cannot accomplish, being it:

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

From what I understand, 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;
}

1 answer

3

In your own text you have:

"Tip: Use integer and module splitting operators".

That’s the real tip. Suppose you read the whole number 42339, as you yourself illustrate.

If you divide it by 10, you give how much?

42339 / 10 = 4233,9

Notice how the comma separates the first digit on the right (not by chance, the 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 in Ideone):

num: 42339 dig: 9 sobra: 4233

I mean, to do one step what you need, just apply this rule (use the module - that is, the rest of the division - by 10 to pick up the digit, and the entire division to keep what is left). So, repeat this procedure for the other steps, until your entire division result is 0 (there is nothing left and you have processed all the digits).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.