I have been trying to incorporate a check to see if the input from the user is a valid input. For example my program wants the user to guess a number between 1-1000. My prog
Here's a snippet I like to keep around for using in these sorts of situations.
int validInput()
{
int x;
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(std:numeric_limits<std::streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
return x;
}
Then any place you want to use cin>>guess, instead, use guess = validInput();
Since spreading around code similar to what @nhgrif suggests for every acquisition is tedious and error-prone, I usually keep around the following header:
#ifndef ACQUIREINPUT_HPP_INCLUDED
#define ACQUIREINPUT_HPP_INCLUDED
#include <iostream>
#include <limits>
#include <string>
template<typename InType> void AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString, InType & Result)
{
do
{
Os<<Prompt.c_str();
if(Is.fail())
{
Is.clear();
Is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Is>>Result;
if(Is.fail())
Os<<FailString.c_str();
} while(Is.fail());
}
template<typename InType> InType AcquireInput(std::ostream & Os, std::istream & Is, const std::string & Prompt, const std::string & FailString)
{
InType temp;
AcquireInput(Os,Is,Prompt,FailString,temp);
return temp;
}
#endif
Usage example:
//1st overload
int AnInteger;
AcquireInput(cout,cin,"Please insert an integer: ","Invalid value.\n",AnInteger);
//2nd overload (more convenient, in this case)
int AnInteger=AcquireInput(cout,cin, "Please insert an integer: ","Invalid value.\n");
The AcquireInput function allows to read any type for which there's an operator>> available and automatically retries (cleaning up the input buffer) if the user inserts invalid data. It also prints the given prompt before asking the data and the error message in case of invalid data.