我是C初学者,我正在尝试创建一个与用户输入一起工作的程序。 问题是,当用户输入不正确的数据时,程序以无限错误循环结束(说“输入数据不正确”)。 我试着fflush并用空字符串清除用户输入,但它只是以某种方式不起作用。C - 无限的错误循环(新手)
MAIN.C:
#include <stdio.h>
#include "nd.h"
#include "nsd.h"
int num1;
int num2;
int a;
//char *p;
int main()
{
while(!feof(stdin))
{
if(scanf("%d %d",&num1,&num2)==2)
{
if ((nd(num1)==1) && (nd(num2)==1))
{
printf("%s\n", "prime");
}
else
{
a=nsd(num1, num2);
printf("%d\n", a);
}
}
else
{
fprintf(stderr, "Incorrect input data...");
//fflush(stdin);
//scanf ("%s",p);
}
}
printf("%s\n", "DONE");
return 1;
}
nd.c:
#include "nd.h"
#include <math.h>
#include <stdlib.h>
int nd(int a) {
// calculate greatest divisor of "a"
// nd equals 1, if it is prime
int ret;
int min_sqrt;
if (a == 1) {
ret = 1;
} else {
min_sqrt = abs(a)/2;
for (ret=min_sqrt; ret>1; ret--) {
if ((a % ret)==0) {
break;
}
}
}
return ret;
}
你有两个'}',所以第二个被关闭while循环。 – NSimon 2014-11-21 09:40:55
@NSimon我认为while循环正确关闭,我已经修复了缩进。 – 2014-11-21 09:44:07
试过程序,这里没有无限循环...如果你在Linux上测试它,在最终输入后尝试Ctrl + D。还要确保函数'nd'和'nsd'终止。 – 2014-11-21 09:45:14