Hello, I have a question about how to limit the input to the following program must be integer.
here is the program, what should I add into it??
thank you!
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double input;
start:
cout << "Enter any number between 1 to 10:";
cin >> input;
if ((input<1)||(input>10))
{
cout << "Please enter the integers 1 through 10" << endl;
goto start;
}
cout << "The square of the number is:" << sqrt(input) << endl ;
goto start;
system ("pause");
return 0;
}
Don't use the goto statement. Forget everything about it you know. Consider it nonexistent.
As to your question: The method istream::fail() will return true if the last input operation on the given istream failed (amongst other reasons). istream::clear() unsets all set error flags of the istream.
So you could do something like:
1 2 3 4 5
int input; //important - obviously input won't fail for double values if you declare this as a double
do {
cin.clear();
cin >> input;
} while(cin.fail());
thank you, so where should i add the do-while?
can i do like this?
int main()
{
int input;
cout << "Enter any number between 1 to 10:";
cin >> input;
if ((input<1)||(input>10))
{
cout << "Please enter the integers 1 through 10" << endl;
}
cout << "The square of the number is:" << sqrt(input) << endl ;
do {
cin.clear();
cin >> input;
} while(cin.fail());
system ("pause");
return 0;
}
No. If you had understood what that code does, you wouldn't be asking such a question.
So understand it fully before trying to band-aid your code with trial and error.
while(cin.fail(Should I put the condition here? ))
int input;
cout << "Enter any integer number between 1 to 10:";
do {
cin.clear();
cin >> input;
} while(cin.fail(input=1 || input=2 || ...........));
cout << "The square of the number is:" << sqrt(input) << endl ;
system ("pause");
return 0;
#include <limits>
#include <cmath>
#include <cctype>
usingnamespace std;
int main()
{
int input;
bool inputIsValid = false ;
while ( !inputIsValid )
{
cout << "Enter any number between 1 to 10:" ;
cin >> input ;
if (!cin)
{ // cin was unable to extract any input that matches our format. Input may be: n333 .333 @#$
cout << "Invalid input detected.\n" ;
// clear error state in cin:
cin.clear() ;
// ignore any input on the current line:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
}
elseif ( !isspace(cin.peek()) )
{ // non space character encountered. Input like 3n2 3.0 1nnnnnn will end up here:
cout << "Invalid input detected.\n" ;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') ;
}
else
inputIsValid = true ;
}
// Note that this is the square root, not the square of the number.
cout << "The square of the number is:" << sqrt(static_cast<double>(input)) << endl ;
}
Now, some input that probably should be accepted here is not: 3. or 3.0, for example are not accepted. There are several different ways you could make that work, but I'll leave it to you to puzzle it out if you should desire to do so.