Turning the user cin>> answer into 3 separate variables to add them together.

I trying to solve this problem below, its actually part of a bigger program but i'll keep the question specific.

This an example of what I’m trying to achieve N = 346 the output should be 3+4+6 = 13

Is there a way I can limit cin >> so the user can only enter 3 digits?

And way I can I make each digit into a separate variable so I can add the 3 number together?

I'm sure there is a simple explanation, thanks

Last edited on
1
2
3
std::cin >> foo;
if ( ! std::cin or foo < 100 or 999 < foo )
  std::cout << "that ain't 3 digits\n";

How you deal with that is up to you.


What can you tell about foo and bar after these statements:
1
2
bar = foo % 10;
foo /= 10;
you can also read 3 char variables and run isdigit on each one. That may make adding them up later easier.
Topic archived. No new replies allowed.