accept integer only from user input

hello.

how can i tell my program to accept only integers? we're making a program about linked list, we have 7 options. when i tried to enter a character (to test the program), it hanged.

here's a piece of the program:

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
int main()
{  
    start_ptr = NULL;
    do
	{
	  cout << endl;
	  cout << "Please select an option : " << endl;
	  cout << "1. Add a node at the start of the list." << endl;
	  cout << "2. Add a node to the end of the list." << endl;
	  cout << "3. Delete the start node from the list." << endl;
	  cout << "4. Delete the end node from the list." << endl;
	  cout << "5. Move the current pointer on one node." << endl;
      cout << "6. Move the current pointer back one node." << endl;
      cout << "7. Exit the program." << endl;

      cout << endl << " --->>> ";
	  cin >> option;

	  switch (option)
	    {
          case 1 : add_start(); break;
	      case 2 : add(); break;
	      case 3 : delete_start(); break;
	      case 4 : delete_end(); break;
	      case 5 : move_current_on(); break;
          case 6 : move_current_back();break;
          case 7: 
               {  information();
                  system("pause>null");
                  exit();
                  break;
               }
          default: cout<<"INVALID INPUT!!";
	    }
	    if (option !=7)
           display();
	}
     while (option != 7);
}


thanks!
The easiest way is to read only strings using getline() and parse the strings into integers.

I would avoid using formatted input operations on std::cin. Users will never type in what you want them to.
If input is only 1 digit you can take it as a char:

1
2
3
4
5
6
7
8
9
10
11
char option;
cin >> option;

switch(option)
{
case '1':  /* note '1' and not 1 */ break;
case '2':  ... break;
...
default:  cout << "Invalid"; break;
}
Topic archived. No new replies allowed.