在C i / o中跳过代码行

时间:2017-04-15 15:07:38

标签: c function input output

在简单程序中学习C时,经常发生计算机跳过某些代码行的执行,我无法理解为什么会这样。

现在作为一个例子,我勾勒出一个程序,它只存储用户输入的3个数字:

#include <stdio.h>

int main(void)
{
int a, b, c;

printf("Please type in number a: \n");
scanf("%i", &a);
printf("Please type in number c: \n");
scanf("%i", &c);
printf("Please type in number b: \n");
scanf("%i", &b);    
return 0;
}

我想输入1,2和3.这是我在控制台中获得的(在Ubuntu中):

Please type in number a:
1
Please type in number b:
Please type in number c:
2

忽略了数字b的输入。

不仅跳过第二个输入,因此即使输入顺序错误也是如此。最初,我在代码中按字母顺序编写了所有内容 - a,b和c,然后跳过了b的输入,然后我更改了代码中的顺序,然后,正如您所见,执行仍保持不变。

我之前遇到过这种情况。

为什么会这样?

1 个答案:

答案 0 :(得分:0)

第二个想法,我认为OP有另一个问题

留下以社区维基作为参考

为了确保输出发生在scanf()之前,请刷新输出。

printf("Please type in number a: \n");
fflush(stdout);
scanf("%i", &a);

printf("Please type in number c: \n");
fflush(stdout);
scanf("%i", &c);

请参阅What are the rules of automatic flushing stdout buffer in C?