Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Menu Guided UI - Switch Statement

$
0
0
Hi All,

I have a menu-based UI where the user inputs a number 0-3, to choose from the options. I'm trying to figure out a way to guard against a user inputting a completely erroneous value (for example 'd' '*' '$' 'q' 'B') -- basically any number that's not between 0-3 (inclusive). I thought the 'default' statement within my switch-statement would guard against any value that isn't 0-3 (erroneous), and then that would break the do-while loop, however that's not what happens. What happens when a user inputs an erroneous value is that it puts the do-while loop into an infinite loop. How can I guard against a user from inputting an erroneous value that will gracefully exit the program? Maybe I'll need an if-statement right after my scanf() statement? Any thoughts would be greatly appreciated! Thanks.

int main()
{     

unsigned short int user_input; 

        do{
        printf(" Press 0 for Jupiter\n\n");
	printf(" Press 1 for Earth\n\n");
	printf(" Press 2 for Mars\n\n");
	printf(" Press 3 for Venus\n\n");
	printf(" --> Any key other than '0'-'3' To Exit Console Application <-- \n\n");

	
	printf("\n\nEnter your choice here --> ");
	scanf("%hu", &user_input);  // %hu scans for an unsigned short

	// you can put an if-statement exit(1) as an ungraceful exit for invalid input values

	switch(user_input)
	{
    
	case 0:
		printf("\nHello Jupiter!\n");
		break;

	case 1:
		printf("\nHello Earth!\n");
		break;

	case 2:
		printf("\nHello Mars!\n");
		break;

	case 3:
		printf("\Hello Venus!\n");
		break;

	default:
		printf("\nWe never reach this.\n\n");
		break;
	}
	
 } while((user_input >= 0) && user_input <= 3); 


return 0;
}



Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>