Force the user to enter ONLY an integer

Trying to figure out how to force the user to enter an integer ONLY when prompted after choosing either 1 or 2 from the menu. Program code below.

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
int main() {
    
    //list is an instance of the DoublyLinkedList class
    DoublyLinkedList list;
    char choice;
    
    //while loop when the choice is not to exit the program
    while(choice != '7') {
        
        cout << "1. Add a new node to the head." << endl;
        cout << "2. Add a new node to the tail." << endl;
        cout << "3. Delete the first node in the list." << endl;
        cout << "4. Delete the last node in the list." << endl;
        cout << "5. Traverse the list reversely." << endl;
        cout << "6. Traverse the list." << endl;
        cout << "7. Exit the program" << endl;
        
        cout << "Please choose an option between 1 and 7." << endl;
        cin >> choice;
        
        //Adds a new node to the head
        if(choice == '1') {
            int number1;
            int val1;
        
            cout << "Please enter a number." << endl;
            cin >> number1;
                val1 = number1;
                list.addHead(val1);
                list.traverse();
                cout << endl;
        }
        
        //Adds a new node the tail
        else if(choice == '2') {
            int number2;
            int val2;
            cout << "Please enter a number." << endl;
            cin >> number2;
                val2 = number2;
                list.addTail(val2);
                list.traverse();
            cout << endl;
        }
        
        //Removes the first node from the head
        else if(choice == '3') {
            int val3;
            val3 = list.removeHead();
            
            if(val3 == -1) {
                cout << "The list is empty." << endl << endl;
            }
            
            else {
                list.traverse();
                cout << endl;
            }
            
        }
        
        //removes the last node from the head
        else if(choice == '4') {
            int val4;
            val4 = list.removeTail();
            
            if(val4 == -1) {
                cout << "The list is empty." << endl << endl;
            }
            
            else {
                list.traverse();
                cout << endl;
            }
            
        }
        
        //prints the list of Nodes in reverse
        else if(choice == '5') {
            list.traverseReverse();
            cout << endl;
        }
        
        //prints the list of Nodes
        else if(choice == '6') {
            list.traverse();
            cout << endl;
        }
        
        //exits the program
        else if(choice == '7') {
            cout << "Goodbye!" << endl;
        }
        
        //input validation
        else {
            cout << "Please only choose a number between 1 and 7." << endl << endl;
        }
    }
}
Last edited on
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
#include <iostream>

// get an int from stdin in the range [minv,maxv]
int get_int( int minv, int maxv )
{
    std::cout << "enter an integer in [" << minv << ',' << maxv << "]: " ;

    int number ;
    if( std::cin >> number ) // if the user  entered an int
    {
        // return it if it is in the range [minv,maxv]
        if( number >= minv && number <= maxv ) return number ;

        // entered int is out of range
        std::cout << "error: the number is out of range. please try again\n" ;
    }

    else // a number was not entered
    {
        std::cout << "error: the input is not an integer. try again\n" ;
        std::cin.clear() ; // clear the failed state of the stream
        std::cin.ignore( 1000, '\n' ) ; // extract and discard the bad input
    }

    return get_int( minv, maxv ) ; // try again (call the same function once more)
}

int main()
{
    std::cout << "Please choose an option. " ;
    const int choice = get_int( 1, 7 ) ;
    std::cout << "your choice is: " << choice << '\n' ;
}
There are two things that must be understood about input to process this.

    1. A user will always press Enter at the end of every requested input.
    2. All user inputs should be accepted as string and then attempted for string→whatever processing second.

There are corollaries:

    1. Input requests should be specific about content and quantity.
    2. To determine if a string→whatever conversion exists, attempt said conversion.

A couple of helper functions are useful:

1
2
3
#include <optional>  // C++17, use <boost/optional.hpp> for older compilers
#include <sstream>
#include <string> 
1
2
3
4
5
6
7
8
9
10
// Convenience helper to convert STRING → WHATEVER
template <typename T>
std::optional <T> string_to( const std::string& s )
{
  T value;
  std::istringstream ss( s );
  ss >> value >> std::ws;
  if (!ss.eof()) return {};  // or boost::none
  return value;
}
1
2
3
4
5
6
7
// Convenience helper to get a STRING from the user
std::string getline( std::istream& ins )
{
  std::string s;
  if (getline( ins, s )) return s;
  return "";
}

This leads to some very clean and robust code:

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
34
35
36
int main()
{
    DoublyLinkedList list;

    while (cin) {
    
        // Ask user for input
        cout << "\n"
          "1. Add a new node to the head\n"
          "2. Add a new node to the tail\n"
          " --snip--\n"
          "7. Exit the program\n"
          "? ";
        string choice = getline( cin );  // get input as STRING!
    
        if (choice == "1") {
            cout << "Please enter an integer to prepend to the list: ";  // be specific
            auto value = string_to <int> ( getline( cin ) );  // Get STRING, try to convert to INT
            if (!value)
                cout << "That was not an integer!\n";
            else {
                list.addTail( *value );
                list.traverse();
            }
        }

        else if (choice == "2") {
        
        --snip--
        
        else if (choice == "7") break;
        
        else cout << "Please only choose a number between 1 and 7.\n";
    }
    cout << "Goodbye!\n";
}

Hope this helps.
Last edited on
Topic archived. No new replies allowed.