C Programming
Validation Of User Input In C
Basic Rules
- Don't pass invalid data onwards.
- Validate data at input time.
- Always give the user meaningful feedback
- Tell the user what you expect to read as input
/* example one, a simple continue statement */
#include <stdio.h>
#include <ctype.h>
main()
{
int valid_input; /* when 1, data is valid and loop is exited */
char user_input; /* handles user input, single character menu choice */
valid_input = 0;
while( valid_input == 0 ) {
printf("Continue (Y/N)?\n");
scanf(" %c", &user_input );
user_input = toupper( user_input );
if((user_input == 'Y') || (user_input == 'N') ) valid_input = 1;
else printf("\007Error: Invalid choice\n");
}
}
Sample Program Output
Continue (Y/N)?
b
Error: Invalid Choice
Continue (Y/N)?
N
/* example two, getting and validating choices */
#include <stdio.h>
#include <ctype.h>
main()
{
int exit_flag = 0, valid_choice;
char menu_choice;
while( exit_flag == 0 ) {
valid_choice = 0;
while( valid_choice == 0 ) {
printf("\nC = Copy File\nE = Exit\nM = Move File\n");
printf("Enter choice:\n");
scanf(" %c", &menu_choice );
if((menu_choice=='C') || (menu_choice=='E') || (menu_choice=='M'))
valid_choice = 1;
else
printf("\007Error. Invalid menu choice selected.\n");
}
switch( menu_choice ) {
case 'C' : ....................(); break;
case 'E' : exit_flag = 1; break;
case 'M' : ....................(); break;
default : printf("Error--- Should not occur.\n"); break;
}
}
}
Sample Program Output
C = Copy File
E = Exit
M = Move File
Enter choice:
X
Error. Invalid menu choice selected.
C = Copy File
E = Exit
M = Move File
Enter choice:
E
Other validation examples
© Copyright B Brown. 1984-1999. All rights reserved.