【发布时间】:2018-10-16 23:50:03
【问题描述】:
我试图让用户输入一个整数,以便稍后在程序中使用我希望它强制用户输入一个输入,直到它是一个整数。当我运行这段代码时,它会像这样进入无限循环:
输入最小运算符:输入最小运算符:输入最小运算符:输入最小运算符:输入最小运算符:输入最小运算符:..........
我认为问题出在扫描仪上,但我不确定应该如何处理它。
#include <stdio.h>
#include <ctype.h>
int main(int argc, const char * argv[]) {
char operator;
int largestOpperator, smallestOpperator;
printf("Enter The Table Operator (+, -, *, /, %%, or R): ");
scanf("%c",&operator);
/*while(!(operator == '+' || operator == '-' || operator == '*' || operator == '/' ||operator == '%' || operator == 'R'))
{
printf("Enter Appropriate Table Operator (+, -, *, /, %%, or R): ");
scanf(" %c",&operator); //requires space as a way to skip the enter when char is scanning!!
}*/
do{
if(!isdigit(smallestOpperator))
printf("Enter smallest operator: ");
else{
printf("Enter an actual number: ");
scanf(" %d", &smallestOpperator);
}
}while(!isdigit(smallestOpperator));
printf("Enter largest operator: ");
scanf("%d", &largestOpperator);
{
printf("Enter a valid integer: ");
scanf("%d", &largestOpperator);
}
return 0;
}
【问题讨论】:
-
你能发布整个程序而不是sn-p吗?
-
不要在代码块中省略
{大括号}。它是吸引错误的磁铁;最好永远不要这样做,这样你就不会犯这些错误了。 -
什么是
smallestOpperator,显示它是如何声明的。还有:smallestOpperator在你的代码之前已经初始化了吗?如果不是,那么您的代码无论如何都是完全错误的。请显示更多相关代码。阅读:minimal reproducible example -
不要使用
scanf进行用户输入。阅读:stackoverflow.com/questions/2144459/… -
isdigit作用于字符,而不作用于整数;但是,您将整数读入smallestOpperator,因此isdigit通常会失败。解决方案:使用scanf中的%c将一个字符读入smallestOpperator。