您的位置:首页 > 其它

fflush(stdin)和rewind(stdin)

2016-03-06 12:09 260 查看
#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, disc, x1, x2, p, q, i;
do
{

scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c);
i = b*b - 4 * a*c;

} while (i<0);
printf("输入正确");

disc = b*b - 4 * a*c;
p = -b / (2 * a);
q = sqrt(disc) / (2 * a);
x1 = p + q, x2 = p - q;
printf("x1=%5.2f\nx2=%5.2f\n", x1, x2);
return 0;
}


在群中有人问了此例,算一元二次方程,scanf()在vs2015中不能用,所以我将其改为了scanf_s()。

当时我认为其输入的:

a=1,b=2,c=3

不满足其输入正确的条件,所以要接着输入a=?,b=?,c=?这些,然而并不能继续输入,按其他键无任何反应,有人回复用fflush(stdin);即可,即:

#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, disc, x1, x2, p, q, i;
do
{
fflush(stdin);
scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c);
i = b*b - 4 * a*c;

} while (i<0);
printf("输入正确");

disc = b*b - 4 * a*c;
p = -b / (2 * a);
q = sqrt(disc) / (2 * a);
x1 = p + q, x2 = p - q;
printf("x1=%5.2f\nx2=%5.2f\n", x1, x2);
return 0;
}


然而在我的vs2015上面仍不能运行,接着我去百度查询。

发生第二次循环无法输入的原因在于输入缓冲区的问题,在读入一个数或字符之后紧接着要读取,此时应该清除输入缓冲区,而fflush(stdin)无法在vs2015中运行,其主要因为该函数功能虽然为:清空输入缓冲区,为确保不影响后面的数据读取。但需注意的是此函数仅适用于部分编译器,如vc6,并非所有编译器都支持这个函数。最合适的做法是加rewind(stdin)。

#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, disc, x1, x2, p, q, i;
do
{
rewind(stdin);
scanf_s("a=%lf,b=%lf,c=%lf", &a, &b, &c);
i = b*b - 4 * a*c;

} while (i<0);
printf("输入正确");

disc = b*b - 4 * a*c;
p = -b / (2 * a);
q = sqrt(disc) / (2 * a);
x1 = p + q, x2 = p - q;
printf("x1=%5.2f\nx2=%5.2f\n", x1, x2);
return 0;
}


或者在紧接着读取之前输出某些:

#include <stdio.h>
#include <math.h>
int main()
{
double a, b, c, disc, x1, x2, p, q, i;
do
{
printf("输入a,b,c:");
scanf_s("%lf%lf%lf", &a, &b, &c);
i = b*b - 4 * a*c;

} while (i<0);
printf("输入正确");

disc = b*b - 4 * a*c;
p = -b / (2 * a);
q = sqrt(disc) / (2 * a);
x1 = p + q, x2 = p - q;
printf("x1=%5.2f\nx2=%5.2f\n", x1, x2);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: