check if input is valid

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
}

thanks
Use the stream function good():

http://www.cplusplus.com/reference/ios/ios/good/

1
2
3
4
5
cin >> x;
if(cin.good())
  alright();
else
  wrong();
closed account (j3Rz8vqX)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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:

http://www.cplusplus.com/reference/ios/ios/clear/
Last edited on
thanks. but the code seems to say "88j9" is "88"...."88j9" is clearly wrong though!!
how do I get around this?
thanks
"88j9" is clearly wrong
Get the input as a string and either test each individual character is a digit, then convert the string to an int.

Or maybe something like this
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <sstream>
#include <string>

using std::cout;
using std::cin;
using std::endl;

int main()
{
    int choice;

    while (true)
    {
        cout << "Please enter an integer: ";
        std::string input, test;        
        cin >> input;
        std::istringstream ss(input);
        bool goodint = (ss >> choice);
        bool goodstr = (ss >> test);
        if (goodint && !goodstr)
            break;
        cout << "Invalid input: " << input << endl;
    }
        
    cout << "The integer was: " << choice << endl;

    return 0;
}


Demo: http://cpp.sh/8kb
Last edited on
amazing
thanks
Topic archived. No new replies allowed.