Hello,

I am creating code that seemed fine, except when I entered a single character, or strings instead of numbers, the console continually prompts for user input and it is difficult to terminate the console. Below is the code

printf("\nHow many computers do you want to update?\n");
scanf("%d", &numComputersToUpdate);

do{
   determineInstallationTargets();
}while (counter < numComputersToUpdate) ;

determineInstallationTargets(); looks fine - except when I enter a character or string

int determineInstallationTargets{
   int menuchoice;
   menuchoice = 0;

   printf("Enter 1 or 2 from menu\n");
   scanf("%d", &menuchoice);

   switch (menuchoice)
   {//start switch menuchoice

		case 1: 
			print ("Case 1\n");
			counter++;
			break;      
		case 2: 
			print ("Case 2\n");
			threadCounter++;
			break;
		default: 
			printf("Please only enter 1 or 2.\n");
			break;
   }//end switch menuchoice
   return 0;

}

I tried using a try-throw-catch block, but it still doesn't catch the error if someone enters a character or string for menuchoice.
Please advise the best way to implement try-throw-catch, or any other method to handle bad input.

Edited 6 Years Ago by rsaska: add clarity to code

No exception is thrown when you enter bad input. Instead, the input stream is set to a fail state. Check using the good() member function.

int n;
  cout << "Enter a number: " << flush;
  while (true)
    {
    cin >> n;
    if (!cin.good())
      {
      cin.clear();  // clear the error state
      cin.ignore( numeric_limits <streamsize> ::max(), '\n' );  // get rid of the bad input
      cout << "Enter a NUMBER ONLY: " << flush;  // complain
      }
    else break;  // otherwise, input worked OK, so escape the loop
    }
  cout << "Good job! You entered the number " << n << ".\n";

Hope this helps.

[edit] Hey, I just noticed you are using C. This is the C++ forum. In C, you need to check the result of scanf() to see how many items were scanned.

Edited 6 Years Ago by Duoas: n/a

For some reason, I thought I was writing in C++.

I'll try it out, thank you!

This article has been dead for over six months. Start a new discussion instead.