C / C ++的printf()scanf函数()之前的问题 [英] C/C++ printf() before scanf() issue
问题描述
我使用Eclipse来code在C / C ++,我有可能是什么东西pretty容易挣扎。在我的code下面我用的printf()
之后 scanf()的
。 Althougth 的printf
之前写scanf()的
输出不同。我能在这里找出一些关于类似问题的。但我没能解决这个问题。任何想法?
code:
的#include<&stdio.h中GT;诠释的main()
{
INT MYVARIABLE; 的printf(请输入一个数字:);
scanf函数(%d个,&安培; MYVARIABLE);
的printf(%D,MYVARIABLE); 返回0;
}
期望的输出:
输入一个数字:1
1
相反,我得到:
1
输入一个数字:1
您输出被缓冲。
你有4个选项:
-
明确刷新
fflush
之后,每次写从缓冲区中获利,仍然执行desiredbehavior /显示明确的。fflush(标准输出);
-
有缓冲区只缓冲行明智
当你知道这是足以只打印完整的生产线非常有用
setlinebuf与(标准输出);
-
禁用缓存
则setbuf(标准输出,NULL);
-
通过什么都选项菜单它提供了在控制台禁用缓存
的例子:
下面是你的code与选项1:
的#include<&stdio.h中GT;
诠释主(){ INT MYVARIABLE; 的printf(请输入一个数字:);
fflush(标准输出);
scanf函数(%d个,&安培; MYVARIABLE);
的printf(%D,MYVARIABLE);
fflush(标准输出); 返回0;
}
下面是2:
的#include<&stdio.h中GT;
诠释主(){ INT MYVARIABLE; setlinebuf与(标准输出); 的printf(请输入一个数字:);
scanf函数(%d个,&安培; MYVARIABLE);
的printf(%D,MYVARIABLE); 返回0;
}
和3:
的#include<&stdio.h中GT;
诠释主(){ INT MYVARIABLE; 则setbuf(标准输出,NULL); 的printf(请输入一个数字:);
scanf函数(%d个,&安培; MYVARIABLE);
的printf(%D,MYVARIABLE); 返回0;
}
I'm using Eclipse to code in C/C++ and I'm struggling with what might be something pretty easy. In my code below I use printf()
and after scanf()
. Althougth printf
is written before scanf()
the output differs. I was able to find out something about similar issue here. But I wasn't able to solve it. Any ideas?
Code:
#include <stdio.h>
int main()
{
int myvariable;
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
Expected output:
Enter a number:1
1
Instead I get:
1
Enter a number:1
Your output is being buffered. You have 4 options:
explicit flush
fflush
after each write to profit from the buffer and still enforce the desiredbehavior/display explicitly.fflush( stdout );
have the buffer only buffer lines-wise
useful for when you know that it is enough to print only complete lines
setlinebuf(stdout);
disable the buffer
setbuf(stdout, NULL);
disable buffering in your console through what ever options menu it provides
Examples:
Here is your code with option 1:
#include <stdio.h>
int main() {
int myvariable;
printf("Enter a number:");
fflush( stdout );
scanf("%d", &myvariable);
printf("%d", myvariable);
fflush( stdout );
return 0;
}
Here is 2:
#include <stdio.h>
int main() {
int myvariable;
setlinebuf(stdout);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
and 3:
#include <stdio.h>
int main() {
int myvariable;
setbuf(stdout, NULL);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
这篇关于C / C ++的printf()scanf函数()之前的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!