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:

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

First of all, after entering a single character, you usually want to call the ignore() function on cin to ignore the rest of the characters in the interval ]first character .. new-line (or enter)] (note the exclusive and inclusive brackets).

Now, if you want a single character input in the console. That is not standard, so, as far as I have seen, this is not possible with any standard function (see the thread on flushing the input buffer). In windows, you can use the header <conio.h> which has this lower-level function called getch() which can get a char directly as it is being typed (with or without echo to the console). If you are in Linux, then the library for it is curses.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.