我真的是c语言的新手。我有以下问题。
如果我使用 scanf() 函数,程序似乎无法正确执行。我正在使用 Eclipse,控制台窗口是空的。但是 - 当我终止 c 程序时,所有内容都显示在控制台窗口中。
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
char c;
char s[10];
float f;
printf("Enter an integer number:");
scanf("%d",&i);
fflush(stdin);
printf("Enter string:");
scanf("%s",s);
fflush(stdin);
printf("Enter a floating number:");
scanf("%f",&f);
fflush(stdin);
printf("Enter a character:");
scanf("%c",&c);
printf("\nYou have entered \n\n");
printf("integer:%d \ncharacter:%c \nstring:%s \nfloat:%f",i,c,s,f);
getch();
}
这是什么原因?
最佳答案
stdout
,printf()
写入,是行缓冲的,所以只有在遇到 \n
时才会刷新。
因此要显示输入提示,您需要显式刷新 stdout
:
printf("Enter an integer number:");
fflush(stdout);
scanf("%d", &i);
在程序终止时缓冲区被隐式刷新,这就是为什么 printf()
ed 数据在程序结束时持续出现在控制台上。
但是,从您发布的源代码中,应该会在执行此行后将数据打印到控制台:
printf("\nYou have entered \n\n");
因为有\n
。所以我假设您没有向我们展示确切的代码。
关于c - 使用 scanf 函数执行 C 程序时控制台窗口为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18672179/