[ back to toc ]

C Problem

Date: 2001/12/22 03:29

Q:
Hi. This is my programme. I'm wondering why, when the FOR loop is
executed, the statement "Please enter colour no. 2: " does not stop and
wait for my input. Instead, it then says that the value for the supposed
input is 7747 and continues to "Please enter colour no. 3: ". Thanks a
lot.

#include <stdio.h>
#define LEN 3

main()
{
int colour_value(char);
int col[LEN], i;
char code[LEN];

printf("The codes for the colours are:\n");
printf("Black = k\n");
printf("Brown = n\n");
printf("Red = r\n");
printf("Orange = o\n");
printf("Yellow = y\n");
printf("Green = g\n");
printf("Blue = b\n");
printf("Violet = v\n");
printf("Grey = e\n");
printf("White = w\n");

for (i=1; i<=LEN; i++)
{
printf("\nPlease enter colour no. %d: ", i);
scanf("%c", &code[i]);
col[i] = colour_value(code[i]);
printf("The value of the colour is %d\n", col[i]);
}
}

/*This function will return the numerical value of a colour*/
int colour_value(char code)
{
int value;

switch(code)
{
case 'k': value = 0;
break;
case 'n': value = 1;
break;
case 'r': value = 2;
break;
case 'o': value = 3;
break;
case 'y': value = 4;
break;
case 'g': value = 5;
break;
case 'b': value = 6;
break;
case 'v': value = 7;
break;
case 'e': value = 8;
break;
case 'w': value = 9;
break;
}
return(value);
}

A:
Thisis because you use scanf not the way you most probably need. You read
a single character using scanf instead of %d.

Also be aware to work up the new line character that is still there on the
input buffer after scanf is executed.

Regards,
Peter

[ back to toc ]