[英]C, Different GCC, fflush() not working?
I'm a beginner programmer. 我是一个初学者程序员。 I have a function that doesn't let float numbers or characters to be inputted.
我有一个不允许输入浮点数字或字符的函数。 It was working fine with gcc 3.4.2, but now I updated to 4.7.1 and it isn't working properly.
它在gcc 3.4.2上运行正常,但现在我更新到4.7.1,但无法正常运行。 It only works now with the first input a[0].
现在仅适用于第一个输入a [0]。 If I input lets say 'x', it will show "Wrong input", however if I input for example '1' for a[0], and then 'x' for a[1], it will still say Input OK and assign '1' to a[1];
如果我输入让我们说“ x”,它将显示“输入错误”,但是,如果我输入例如“ 1”代表a [0],然后输入“ x”代表a [1],它仍然会说输入OK和将“ 1”分配给a [1]; How can I fix this?
我怎样才能解决这个问题? Thank you!
谢谢!
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");
}
You should check the return value of scanf
. 您应该检查
scanf
的返回值。 It returns the number of items it managed to "scan", which will be zero if it failed to scan anything, for example when you input 'x'
: 它返回它设法“扫描”的项目数,如果它未能扫描任何内容,例如当您输入
'x'
时,它将为零:
if (scanf("%lf", &q) == 1)
{
printf("Input OK.\n");
a[x] = q;
}
else
{
printf("Wrong Input\n");
x--;
}
I suggest to you to replace 我建议你更换
scanf("%lf", &q);
with 与
while ((c=(scanf(" %lf%c", &q, &tmp) !=2 || !isspace(tmp)))
|| (q != (unsigned int) q)) {
printf("Your input is invalid please enter again: ");
if(c) scanf("%*[^\n]");
}
The scanf("%*[^\\n]");
scanf("%*[^\\n]");
clean your stdin so no need any more for fflush(stdin)
in your code 清理您的标准输入,因此在代码中不再需要
fflush(stdin)
So your code could be: 因此,您的代码可能是:
void initArray(unsigned int a[]) {
double q;
int x, c=0;
char tmp;
for ( x = 0; x < SIZE; x++){
printf("a[%d] ", x);
printf("Enter number: ");
while ( (c=(scanf(" %lf%c", &q, &tmp) !=2 || !isspace(tmp)))
|| (q != (unsigned int) q)) {
printf("Your input is invalid please enter again: ");
if(c) scanf("%*[^\n]");
}
a[x] = q;
}
printf("\n");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.