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?
The problem is because of trailing newline characters after your second call to scanf() .
If you have multiple format specifiers within the string argument of scanf, you can input multiple values. All you need to do is to separate each format specifier with a DELIMITER - a string that separates variables.
When you enter the character, you have to enter a whitespace character to move on. This whitespace character is present in the input buffer, stdin file, and is read by the scanf() function. This problem can be solved by consuming this extra character.
scanf("%d") reads the 1 and the 5 , interpreting them as the number 15 , but the newline character is still in the input buffer. The scanf("%c") will immediately read this newline character, and the program will then go on to the next scanf("%d") , and wait for you to enter a number.
scanf("%c")
reads the newline character from the ENTER key.
When you type let's say 15
, you type a 1
, a 5
and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d")
reads the 1
and the 5
, interpreting them as the number 15
, but the newline character is still in the input buffer. The scanf("%c")
will immediately read this newline character, and the program will then go on to the next scanf("%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 a getchar()
after each scanf("%d")
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With