【发布时间】:2019-10-06 03:56:14
【问题描述】:
我有一个函数要求用户输入一个值来计算其平方根,但是当我尝试验证输入的数字必须是数字而不是字符时,它会产生无限循环
void opcion1(void){
float A, K, i, aux;
int awnser;
ask:
fflush( stdin );
printf("enter the value for A: ");
sleep(1);
awnser = scanf("%f", &A);
if(awnser < 1){ // not a number
fputs("\nA is not a number\n", stderr);
goto ask;
}
if(A < 0 ){
aux = -A;
i = sqrt(aux);
if(A == (int)A) printf("\nthe square root of %.0f, is%.0fi", A, i);
else printf("the square root of %.3f, is %.4fi", A, i);
}else{
K = sqrt(A);
printf("the square root of A is %.2f", K);
}
}
输出:
enter the value for A:
k
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
【问题讨论】:
-
你的意思是,如果你输入
k,你会无限打印这两行? -
问题是
fflush(stdin)。 C 标准只允许在输出流上使用fflush,而不是在输入流上。解决问题的一种方法是读取带有fgets的一行,然后使用sscanf解析数字。 -
因为
scanf()在输入缓冲区中留下未被接受的字符,如果您尝试读取数字并且输入中有非数字(例如字母或标点符号)缓冲区,你得到一个无限循环。测试scanf()是否成功。如果没有,通常的技巧是使用像{ int c; while ((c = getchar()) != EOF && c != '\n') ; }这样的循环(所以有一个空循环体)。如果scanf()报告 EOF,您的 shell 应该可能退出。
标签: c validation scanf goto