Jump to content
  • Advertisement
Sign in to follow this  
mckoo

data validation!?

This topic is 5053 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
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. :)

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
`_getch()' is not a part of either C or C++.
To the OP: Try getchar() and then use '0', '1', ... .

-Pete

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!