我有以下函数来过滤整数值并重新提示用户。
int checkInput0(void){
int option0,check0;
char c;
do{
printf("Enter the amount of triangles you want to check: \n");
if(scanf("%d%c",&option0,&c) == 0 || c != '\n'){
while((check0 = getchar()) != 0 && check0 != '\n' && check0 != EOF);
printf("[ERR] Invalid number of triangles.\n");
}else{
break;
}
}while(1);
// printf("returning the value of option, which is %f", option);
return option0;
但是,我想扩展此功能以过滤0。
我似乎错过了一些东西。非常感谢所有帮助。提前致谢!
答案 0 :(得分:1)
发布的代码未正确检查'scanf()'返回的值,并且不能完全执行所需的功能。
以下提议的代码:
现在建议的代码:
do
{
printf("Enter the amount of triangles you want to check: \n");
if( scanf( "%d", &option0 ) == 1 )
{
if( 0 >= option0 )
{ // 0 or negative value entered
printf("[ERR] Invalid number of triangles.\n");
continue;
}
// empty stdin
while( (check0 = getchar()) != EOF && check0 != '\n' );
// exit while() loop
break;
}
else
{ // scanf failed
perror( "scanf for number of triangles failed" );
exit( EXIT_FAILURE );
}
} while(1);