Sign in to follow this  

data validation!?

This topic is 4842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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. :)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this