accept only one character from user input

i'm having a problem on the program we're tasked to do.

originally, the "option" is an int but someone suggested to make it a character. i thought the problem was solved (i want to make the program print: "invalid output" if the user inputted non-numerical values) but when i tried to enter 11, 12, etc. it didn't go to the default part. i understand that even if you enter many characters, only one character will be read. the problem is how can allow my program to enter only one character? also, is it possible that after the user inputted a number, it function will be executed? (i mean, i don't have to enter, it will just execute automatically.)

thanks!


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');
}


note: option is a global variable. the program is very long that's why i didn't post it.
Is option defined as a char?

If it is, then cin >> option will only get the first character inputted. So "11" will fall in case '1', "20" will fall under case '2', etc.

You need to declare option as an std::string. This way, cin >> option will catch the entire input . And then change the cases to "1", "2", etc.
Topic archived. No new replies allowed.