Get the input as a string then check each of the characters. If all is ok then convert that string to int (or other data type). Something along these lines.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int gallons;
std::string input;
cout << "Enter gallons\";
cin >> input;
bool ok = true;
for(int i = 0; i < input.length(); i++)
{
if( !isdigit(input[i]) )
{
cout << "Error\n";
ok = false;
}
}
if( ok == true )
{
stringstream str(input);
str >> gallons;
}
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
if you don't want to get the user's input as a string you can
do the following (not tested) :
int num = 0;
cout<<"Number please : ";
cin >> num;
while(!cin)//if input fails
{
cin.clear();
while(cin.get() != '\n')
continue;
cout<<"\nInvalid Input\n";
cout<<"Try again : ";
cin >> num;
}
firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608