以下是主要功能我需要检查我的数组输入是整数还是alpha,但是我的程序一直在循环
int main (void) {
int i;
float arr[3];
for(i=0; i<3; i++){
printf("Enter the weight of the cabin %d:t", i+1);
scanf("%f", &arr[i]);
if(isdigit(arr[i])){
*im not sure about this part*
printf("Cabin %d is %.2fn", i+1, arr[i]);
}else{
printf("Error! Please enter the weight of the cabin %d again:t", i+1);
scanf("%d", &arr[i]);
printf("Cabin %d is %.2fn", i+1, arr[i]);
}
if(i==2){
i=0-1;
}
}
}
我希望我的输出会像:
输入机舱的重量:r错误!请再次输入机舱的重量:
但是,我明白了。输入机舱的重量:R它像疯了一样循环,我看不到屏幕上出现的内容
isdigit()
可用于检查单个字符。您传递给它的是浮子(可能完全畸形)。您需要做的是将输入读为字符串,并检查每个字符,直到遇到' 0'。
除此之外,您的程序继续循环的原因是
if(i==2){
i=0-1; // i = -1;
}
您永远不会让我超越2以使循环停止。
正在发生的事情是scanf
失败,而无需删除stdin
的字母顺序文本。这意味着下一个scanf
也失败,依此类推。
您需要检查scanf
的返回值,如果未能扫描数字,则需要从stdin
中删除非数字输入。我建议在scanf
失败时使用fgets
从stdin
中删除一条输入。
while (1 != scanf("%f", &arr[i])) {
// Scan failed! Remove input line with non-numeric input
char tmp[100];
fgets(tmp, sizeof tmp, stdin);
printf("Not a number! Enter the weight of the cabin %d:t", i);
fflush(stdout);
}