data validation!?

Started by
4 comments, last by Pete_ 19 years, 7 months ago

int main()
{
		int exit_flag = 0;
		int ch;
		while(exit_flag == 0){
			printf("XXX Secondary School Students' Union\n");
			printf("1. Add new member information\n");
			printf("2. Print member list\n");
			printf("3. Exit\n");
			printf("Please enter the choice: ");
			scanf("%d", &ch); 

			switch(ch){
			case 1: input_screen(); break;
			case 2: read_data(); break;
			case 3: exit_flag = 1; break;
			default: printf("Fal"); break;
			}

		}
		exit(1);
		return 0;
}

it works fine with digits....however when i type in a character, it look infinitely.....why this occurs? i tried with ch = getchar()...still doesn't work...... any replies are appreciated
Advertisement
The %d in your scanf means 'format input from the keyboard into a decimal' (i.e. a number), which is why it probably isn't working. If you want to be more flexible, try something like:

char input[80];scanf("%s", input);


This will read the input into a string of characters. Of course, this isn't a good solution if you really need it to reply to a single keypress. If you can tell me more about what you need it to do I can probably suggest more. :)
---PS3dev
scanf relies on the format specification to determine how to interpret the data entered. Mismatches between that specification and the actual data entered can cause extra data to remain in the buffer, or too little to be placed. For example, the %d specification indicates an integer, which is 32 bits wide in most contemporary environments. Entering a character yields the integral interpretation of that character, which is only an 8-bit ASCII code. scanf still expects 24 more bits, so it waits, or something like that.

The robust way to handle this is to always read input as a string and then parse that string for data.
thx~~
but i do really want a single keypress.....
so may i use itoa?
What about _getch()?
`_getch()' is not a part of either C or C++.
To the OP: Try getchar() and then use '0', '1', ... .

-Pete

This topic is closed to new replies.

Advertisement