cin.fail

Jun 3, 2016 at 4:23pm
I am trying to get the input "index" to be analyzed for "integer" or "non-int". This does not seem to be working for me.It seems straightforward: what is(are) my errors.Compiles fine. But every number I input returns "Integer".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<string>

int main()
{
    int index;
        std::cout << "Enter an index: ";
        std::cin >> index;

        //handle case where user entered a non-integer
        if (std::cin.fail())
        {
            std::cout<<"Non-integer";

        }

        else
        {
        	std::cout<<"Integer";
        }


    return 0;
}
Last edited on Jun 3, 2016 at 4:29pm
Jun 3, 2016 at 4:28pm
But every number I input returns "Integer".

What were you expecting? If the first character is a digit or a sign character (+ -) then the entry is a valid integer, even if there is some other non digit character after the first digit.



Jun 4, 2016 at 2:48pm
got it, thx
was just using numbers
Topic archived. No new replies allowed.