I have been trying to make a very simply programme that checks if the inputted information is an integer or not (i.e: that it contains no other characters).
I have tried using the isdigit function (but this only works for single characters)
i have tried cin.clear, cin.ignore (1000) but this doesn't work either..
can someone please suggest an effective way to check if x in the following programme has been entered correctly
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter an integer (positive or negative)" << endl;
int x;
cin >> x; HERE I WOULD LIKE CODE TO CHECK IF THE USERS INPUT IS VALID
}
#include <iostream>
using std::cout;
using std::cin;
int main()
{
int choice;
bool error;//Our error flag
do
{
error = false;//Flag false, safe
cout<<"Enter a integer value: ";
cin>>choice;
if(cin.fail())
{
error = true;//Flag true, error has occurred
cout<<"Error, invalid entry.\n\n";
}
cin.clear(); //Clears any error flags
cin.ignore(1000,'\n'); //Ignores 1000 characters, or until '\n'
}while(error);
cout<<"\nThe integer value entered was: "<<choice<<'\n';
cout<<"Press <enter> to exit console: ";
cin.get();
return 0;
}
Enter a integer value: d
Error, invalid entry.
Enter a integer value: s
Error, invalid entry.
Enter a integer value: a
Error, invalid entry.
Enter a integer value: 50
The integer value entered was: 50
Press <enter> to exit console: