View Single Post
  #6 (permalink)  
Old 04-15-2007, 11:57 AM
v0id's Avatar   
v0id v0id is offline
Super Moderator
 
Join Date: Apr 2007
Location: Denmark
Posts: 2,452
Last Blog:
CherryPy(thon)
Rep Power: 27
v0id is a glorious beacon of lightv0id is a glorious beacon of lightv0id is a glorious beacon of lightv0id is a glorious beacon of lightv0id is a glorious beacon of lightv0id is a glorious beacon of light
Send a message via MSN to v0id
Default

First of all, try learn to use the [ code ]-tags.

The problems you have is because you don't use the fflush()-function. When something is entered through the input-stream (stdin) during execution of the application, it will mostly stay in there. When it then tries to get some new stuff through the stream, it will sometimes be... yeah, strange. When using fflush() and stdin together, the stdin will be cleared and you can retrieve new input, without worry.

I've made minor changes to your application, actually I've only inserted the fflush()-function, two times. I've commented the code those placed, so you get what's going on.
Code:
#include <stdio.h>

int main()
{
	int  i, type;
	char c;
	
	type = 0;
	
	printf("ASCII character program\n\n");
	while(type != 'q')
	{
		printf(" Input 1, 2, 3, or q\n");
		printf(" 1: ASCII code -> CHAR\n");
		printf(" 2: CHAR -> ASCII code\n");
		printf(" 3: DISPLAY ASCII TABLE\n");
		printf(" q: End of this Program\n");
		printf(">>");
		scanf("%c", &type);
		
		/*\
		|*|		First we get some input from the user, into 
		|*|		_type_, through the stdin (Standard Input Stream).
		|*|		Then, before we're retrieving new data
		|*|		(in the if-statement) we have to clear it.
		|*|		This is done with fflush().
		\*/
		fflush(stdin);
		
		if(type == '1')
		{
			printf("ASCII code -> CHAR\n");
			printf(" Input ASCII code: ");
			scanf("%d", &c);
			printf(" Character for ASCII code %d is -> '%c'\n\n", c, c);
		}
		else if(type == '2')
		{
			printf("CHAR -> ASCII code\n");
			printf(" Input a character: ");
			scanf("%c", &c);
			printf(" ASCII code for character '%c' is -> '%d'\n\n", c, c);
		}
		else if(type == '3')
		{
			printf("ASCII code table for 1-127\n");
			for(i = 1; i <= 127; i++)
				printf("Character for ASCII code %d is -> '%c'\n", i, i);
		}
		
		/*\
		|*|		Now we got something into _c_, and before
		|*|		the loop starts over again, we need to clear
		|*|		it before we again will retrieve something in _type_.
		\*/
		fflush(stdin);
	}
	
	return 0;
}
Reply With Quote