How do I force users to input integers only in my program?

Pages: 12
Aug 5, 2015 at 3:34pm
closed account (48T7M4Gy)
The core issue for me is the testing of cin to handle the three limitations of a single input which is a simple one-liner. Looping around until the input satisfies the contract was secondary to the OP. We don't have enough information to know what is right or wrong here primarily because such assessments miss the point of the OP.
Last edited on Aug 5, 2015 at 3:35pm
Aug 7, 2015 at 8:47am
closed account (48T7M4Gy)
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
30
31
32
33
/*
 Checks that input is an integer and within the set limits
 */

#include <iostream>

int main()
{
    
    std::cout << "Please enter a number between 1 and 7: " << std::endl;
    
    bool keepGoing = true;
    
    int x = -1;
    
    while(keepGoing == true)
    {
        std::cin >> x;
        if( !std::cin || x < 1 || x > 7 )
        {
            std::cout << "OOPS\n";
        }
        else
        {
            std::cout << "Bingo " << x << '\n';
        }
        
        std::cin.clear(); //clears error flags
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');//clears buffer
    }
    
    return 0;
}
Aug 7, 2015 at 9:28am
@duoas Thanks. I thought about it and yeah there is a way to do it with strcmp but it'd be much longer and involve too many if elses to remain efficient. ignore is the way to go.
Aug 7, 2015 at 12:28pm
closed account (48T7M4Gy)
I can't see any need for strcmp and cin.ignore() is not complete without cin.clear(). Try it by commenting out my line 28. In short, if you don't use clear then the stream will be in a permanent error state.
Topic archived. No new replies allowed.
Pages: 12