If a user inputs a int number, say 150, how would I be able to read each individual number?

i.e., I want to read the 1, do some things with it, then read the 5, and the next number...etc.


7 Years
Discussion Span
Last Post by firstPerson

Either read it in as a string and access the digits as characters, or get the remainders after division by 10, subtract remainder, division by 100, etc.

Please post your attempt and someone will look it over.

Edited by jonsca: n/a


You can use cin.get() to read each individual characters from the stream.

... read it in as a string and access the digits as characters...

How do these suggestions support

If a user inputs a int number, say 150...

:icon_question: :icon_rolleyes:

As jonsca alluded to, look up the modulus (%) operator. Used in conjunction with division you will have your answer.

Edited by WaltP: n/a


I was offering string input as an alternative to the "int number," but you're right based on his specifications.

Edited by jonsca: n/a


>>How do these suggestions support......."If a user inputs a int number, say 150..."

Easy conversion from char to int and easy error checking:

char ch = cin.get();
if(isdigit(ch)) int num = ch - '0';
else { alertError("Invaild input"); }

or for OP a better example :

char input = 0;
while( cin.get(input) ){
 if( isdigit(input) ) cout << input << endl;
 else { break; }

Edited by firstPerson: n/a

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.