Menu Validator:
C
Easy
4 views
Problem Description
Show the user a menu (1-5 options). If they enter anything other than a number (character, symbol), detect scanf fail, clear the buffer, and try to input mango again.
Official Solution
#include <stdio.h>
int main() {
int choice;
int status;
while (1) {
printf("n---- MENU ----n");
printf("1. Applen");
printf("2. Bananan");
printf("3. Mangon");
printf("4. Orangen");
printf("5. Exitn");
printf("Enter your choice (1-5): ");
status = scanf("%d", &choice);
// If scanf fails (non-number input)
if (status != 1) {
printf("Invalid input! Please enter a number.n");
// Clear input buffer
while (getchar() != 'n');
continue;
}
// Check range
if (choice < 1 || choice > 5) {
printf("Invalid choice! Please select between 1 and 5.n");
continue;
}
// Valid input
break;
}
if (choice == 5) {
printf("Exiting program.n");
} else {
printf("You selected option %d.n", choice);
}
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!