以下是一个简单的C程序:
#include <stdio.h>
int main(void)
{
//Question 2.16
//Variables that will be used to store the two numbers
int num1;
int num2;
//Message to prompt the user
printf ("Enter two numbers\n");
//Accepting the users input
scanf("%d %d" , &num1, &num2);
if (num1 > num2) {
printf("%d is greater\n", num1); // Print num1 if num1 is greater
}
else { //Otherwise print that num1 is not greater
printf("%d is not greater\n", num1);
}
return 0; // End of program
}但是当我构建和运行程序(我使用的IDE是Eclipse )时,我必须在执行第一个printf语句之前输入变量num1和num2的值。有关控制台输出,请参见以下内容:
输入两个数字2不大于2
我的问题很简单:为什么会发生这种事?欢迎任何解释。
发布于 2019-08-22 14:23:25
printf(...)函数将输出放入输出流的缓冲区中。因此,有时可能会在某个时候之后显示输出。
scanf(...)函数使用输入流。
这两个函数都涉及独立的流,并且由于缓冲,结果可能不像代码那样是连续的。强行冲洗任何溪流
int fflush(FILE *stream);是使用的。
请使用
fflush(stdout);在print语句之后获得所需的输出。
发布于 2019-08-22 17:23:47
我的建议如下:
(1)显式而不是隐式地使用流:例如,更喜欢fprintf(stdout, "Enter two numbers\n"); fflush(stdout);而不是printf ("Enter two numbers\n");。对scanf函数应用相同的规则--即更喜欢使用fscanf和流(例如,stdin)。
(2) 不让一次只输入一个scan函数--这会导致流以无法计算的意外方式发生故障:因此,更倾向于fscanf(stdin, "%d", &num1); fscanf(stdin, "%d", &num2);而不是scanf("%d %d", &num1, &num2);。
发布于 2019-08-22 14:16:26
尝试在fflush语句和printf语句之间使用scanf:
// Message to prompt the user
printf("Enter two numbers\n");
fflush(stdout);
// Accepting the user's input
scanf("%d %d", &num1, &num2);https://stackoverflow.com/questions/57611124
复制相似问题