How to not accept letters after numbers for an int?

Basically I'm trying to make error messages for invalid cin inputs, but I'm finding that when I put letters after numbers for integer values it just reads the numbers and then carries the letters over to the next line. I want that input to make cin fail instead, but I have no idea how to do that.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
    int x = 0;
    cin >> x;
    while (!(cin))
    {
        cin.clear();
        cout << "Invalid";
        cin.ignore(1000, '\n');
        cin >> x;
    }
}


This code puts out invalid for letters, for letters then numbers, but not for numbers then letters. ie "100fdsjksfd" is a valid input, and I want that to make cin fail as well.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cctype>

int main()
{
    int x = 0;

    // loop till
    // a. an integer is successfully extracted ie. bool( std::cin >> x ) == true
    //    see: http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool
    //
    // and b. the immediately following character in the input buffer is a white space
    //     peek: http://en.cppreference.com/w/cpp/io/basic_istream/peek
    //     isspace: http://en.cppreference.com/w/cpp/string/byte/isspace
    while( !( std::cin >> x && std::isspace( std::cin.peek() ) ) )
    {
        std::cin.clear();
        std::cout << "invalid input\n";
        std::cin.ignore( 1000000, '\n' );
    }

    std::cout << "x == " << x << '\n' ;
}
Topic archived. No new replies allowed.