C:多scanf函数的,当我在一个scanf函数的值输入跳过第二scanf函数 [英] C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf
问题描述
我有code(省略的逻辑功能是家庭作业的一部分)的此块:
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;
}
前两个scanf函数的工作很好,没有任何问题,一旦我们进入while循环,我在哪里,你都应该被提示输入一个新的形状字符时出了问题,而是跳下来的的printf
,并等待接受输入从那里为一个字符,后来小数环路的下一次迭代。
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迭代:
Preloop iteration:
scanf函数:形状。伟大的工程结果
scanf函数:长度。没有问题
Scanf: Shape. Works Great
Scanf: Length. No Problem
1,循环
scanf函数:形状。跳过这一结果
scanf函数:长度。问题,这scanf函数映射到形状字符。
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.
回路2结果
scanf函数:形状。跳过这一结果
scanf函数:长度。的问题,这个现在scanf函数映射到大小INT。
Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.
为什么这样做呢?
推荐答案
scanf函数(%C)
读取来自换行符<大骨节病> ENTER 骨节病>键。
当你键入假设 15
,您键入 1
,一个 5
然后preSS的<大骨节病> ENTER 骨节病>键。所以现在有在输入缓冲区中三个字符。 scanf函数(%D)
读 1
和 5
,除preting他们作为数 15
,但换行符仍然在输入缓冲区。在 scanf函数(%C)
将立即读这换行符,然后程序将进入下一个 scanf函数(%d个 )
,并等待你输入一个号码。
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.
通常的建议是读取输入的整行以与fgets
,和跨preT每行的一个单独的步骤中的内容。一个简单的办法,以你的眼前的问题是添加的getchar()
之后每个 scanf函数(%D)
。
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")
.
这篇关于C:多scanf函数的,当我在一个scanf函数的值输入跳过第二scanf函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!