I am just trying to write a simple program that reads from cin, then validates that the input is an integer. If it does, I will break out of my while loop. If not, I will as
Don't use using namespace std; Instead import what you need.
It's better to do input a line at a time. This makes behavior much more intuitive if you have multiple words on one line, or if you press enter before typing anything.
#include
#include
#include
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;
int main() {
int input;
while (true)
{
cout << "Please enter an integral value: " << flush;
string line;
if (!getline(cin, line)) {
cerr << "input failed" << endl;
return 1;
}
istringstream line_stream(line);
char extra;
if (line_stream >> input && !(line_stream >> extra))
break;
}
cout << input << endl;
return 0;
}