In order to exclude all cases where user input some invalid input (like when you expect an int and get a string) you need to get the input as string (e.g.
std::string
).
Also since at least one input need to be entered you can use
do..while
loop.
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
|
#include <iostream>
#include <cctype>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
int c;
std::string s;
cout << "Please enter a 5-digit number!" << endl;
do
{
cin >> s;
if(s.size()!=5)
{
cout << "You entered: " << s << "\nPlease enter a 5-digit number ";
continue;
}
else if(isdigit(s[0]) & isdigit(s[1]) & isdigit(s[2])
& isdigit(s[3]) & isdigit(s[4]))
{
c = atoi(s.c_str());
break;
}
}while(1);
cout << "Number is " << c;
return 0;
}
|
I will try to explain the code above:
I declare 2 variables: 1 int for storing the number you want and 1 string to store the string the user enters.
I start an infinite loop
do.. while(1)
that will never stop until I use
break
. I could use a condition in while to set it to false with the same result.
1 2 3 4 5 6 7
|
condition = true;
do
{...
//(when it's time)
condition = false;
...
}while(condition)
|
if(s.size()!=5)
this checks if input has 5 characters. If it doesn't it just reloops (continues to next loop with
continue;
) and if it does where this condition is false
it checks again if the (now 5) characters are all digits:
1 2
|
else if(isdigit(s[0]) & isdigit(s[1]) & isdigit(s[2])
& isdigit(s[3]) & isdigit(s[4]))
|
Here is the same as using && but faster since this is binary AND. So it could be
1 2
|
else if(isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2])
&& isdigit(s[3]) && isdigit(s[4]))
|
with no difference
If they are (above condition is true) the it does 2 things:
First
c = atoi(s.c_str());
converts
string
to
char *
in other words converts
std::string
to c string (from c++ to c) because
atoi
expects a
char *
argument
atoi()
converts char * (that is c string) to int. So by the combination
c = atoi(s.c_str());
we get the number we want.
Now we don't need to loop any more so we break the loop (using
break;
)
The main parts are that you get an input and check to see if it's OK. If it is then continue using it as you please. If on the other hand it does not the ask again for an input until you get a proper input.
Hope it helped