if numInput isnt an integer I want it to prompt "Invalid Try Again" and ask
for input again
std::cout << "Enter a Number (Max 10 digits)(99 to Exit): ";
std::cin >> numInput;
Here's an example based on your request:
#include <iostream>
int main(){
double numInput;
while(true){
std::cout << "Enter a Number (Max 10 digits)(99 to Exit): ";
std::cin >> numInput;
if( numInput - static_cast<int>(numInput) != 0.0 )
std::cout << "Invalid Try Again" << std::endl;
else
break;
}
if( numInput == 99.0 )
return 0;
std::cout << "You entered: " << static_cast<int>(numInput);
return 0;
}
Here's an example based on your request:
#include <iostream> int main(){ double numInput; while(true){ std::cout << "Enter a Number (Max 10 digits)(99 to Exit): "; std::cin >> numInput; if( numInput - static_cast<int>(numInput) != 0.0 ) std::cout << "Invalid Try Again" << std::endl; else break; } if( numInput == 99.0 ) return 0; std::cout << "You entered: " << static_cast<int>(numInput); return 0; }
Why if you type "g"? That's not an integer either, but it throws your program into an infinite loop because cin is put into an error state. The usual pattern for validating input works like so:
#include <iostream>
#include <ios>
#include <limits>
int main()
{
int value;
while (std::cout<<"Please enter an integer: ", !(std::cin>> value)) {
// Clear the stream state so we can flush
std::cin.clear();
// Flush all input on the current line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Notify the user of an error
std::cerr<<"Invalid input. ";
}
std::cout<<"You entered "<< value <<'\n';
}
Of course, stream input isn't quite as easy as we would sometimes like. 123.456
will succeed and place 123
in value
while leaving ".456" in the stream. To protect against this kind of error (if it's an error in your app), you also need to peek the next character and verify that it's either a newline or end-of-file (optionally trimming trailing whitespace if you feel especially persnickety):
#include <iostream>
#include <ios>
#include <limits>
#include <cctype>
bool valid_state(std::istream& in)
{
if (!in)
return false;
else {
std::istream::int_type c;
while ((c = in.peek()) != '\n' && std::isspace(c)) {
// Trim a non-newline whitespace character
in.get();
}
return c == '\n' || c == EOF;
}
}
int main()
{
int value;
while (std::cout<<"Please enter an integer: ", !valid_state(std::cin>> value)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cerr<<"Invalid input. ";
}
std::cout<<"You entered "<< value <<'\n';
}
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.