I have this block of code (functions omitted as the logic is part of a homework assignment):
#include <stdio.h>
int main()
{
char c = 'q';
int size;
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("Length:");
scanf("%d",&size);
while(c!='q')
{
switch(c)
{
case 'l': line(size); break;
case 's': square(size); break;
case 't': triangle(size); break;
}
printf("\nShape (l/s/t):");
scanf("%c",&c);
printf("\nLength:");
scanf("%d",&size);
}
return 0;
}
The first two Scanf’s work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the printf of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop.
Preloop iteration:
Scanf: Shape. Works Great
Scanf: Length. No Problem
Loop 1.
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.
Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.
Why is it doing this?
scanf("%c")reads the newline character from the ENTER key.When you type let’s say
15, you type a1, a5and then press the ENTER key. So there are now three characters in the input buffer.scanf("%d")reads the1and the5, interpreting them as the number15, but the newline character is still in the input buffer. Thescanf("%c")will immediately read this newline character, and the program will then go on to the nextscanf("%d"), and wait for you to enter a number.The usual advice is to read entire lines of input with
fgets, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add agetchar()after eachscanf("%d").