gpt4 book ai didi

C,不同的 GCC,fflush() 不工作?

转载 作者:太空宇宙 更新时间:2023-11-04 07:28:49 25 4
gpt4 key购买 nike

我是一名初级程序员。我有一个不允许输入 float 或字符的函数。它在 gcc 3.4.2 上工作正常,但现在我更新到 4.7.1 并且它不能正常工作。它现在只适用于第一个输入 a[0]。如果我输入'x',它会显示“错误输入”,但是如果我输入例如'1'代表a [0],然后输入'x'代表a [1],它仍然会说Input OK并且将“1”分配给 a[1];我怎样才能解决这个问题?谢谢!

void initArray(unsigned int a[]) {

double q;
int x, c;

for ( x = 0; x < SIZE; x++){
printf("a[%d] ", x);
printf("Enter number: ");

scanf("%lf", &q);

if (q == (unsigned int) q) {
printf("Input OK.\n");
a[x] = q;
fflush(stdin);
}
else {
printf("Wrong Input\n");
fflush(stdin);
x--;
}
}
printf("\n");
}

最佳答案

您应该检查scanf 的返回值。它返回它设法“扫描”的项目数,如果它没有扫描任何东西,该数字将为零,例如当您输入 'x' 时:

if (scanf("%lf", &q) == 1)
{
printf("Input OK.\n");
a[x] = q;
}
else
{
printf("Wrong Input\n");
x--;
}

关于C,不同的 GCC,fflush() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15762591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com