我正在使用scanf(带循环)将整数分配到数组中。我希望用户只输入8个整数(它将在一行上),进入终端。如果他们输入9个数字,我希望程序打印错误信息。
我试图将if语句与scanf结合起来。
int main(){
int input[8] = {0};
int countM = 0;
while(countM < 9){
if(scanf("%d", &input[countM]) < 8){
countM++;
} else{
printf("Invalid input");
exit(0);
}
}
return(0);
}
它没有检测到第9个输入。我希望它输出“无效输入”。
你说输入将全部在一行上。因此,输入一行到字符串并检查出来。这会尝试扫描第9个输入。
int input[8] = { 0 };
char dummy[8];
char buff[200];
if(fgets(buff, sizeof buff, stdin) == NULL) {
exit(1); // or other action
}
int res = sscanf(buff, "%d%d%d%d%d%d%d%d%7s", &input[0], /* etc */, &input[7], dummy);
if(res != 8) {
exit(1); // incorrect inputs
}
这是一个完整的工作示例,从@AnttiHaapala评论改进并减少接受两个数字而不是8。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int input[2] = { 0 };
char dummy;
char buff[200];
if(fgets(buff, sizeof buff, stdin) == NULL) {
exit(1); // or other action
}
int res = sscanf(buff, "%d%d %c", &input[0], &input[1], &dummy);
if(res != 2) {
exit(1); // incorrect inputs
}
puts("Good");
}
我们来看看你的代码。
int input[8] = {0}; // (1)
int countM = 0;
while(countM < 9){
if(scanf("%d", &input[countM]) < 8) // (2)
...
}
在(1)中,定义一个长度为8的数组。在(2)中,你有一个循环,它通过9个整数(从0到8)。在循环的最后一次运行期间,你有相应的
scanf("%d", &input[8] < 8)
这超出了数组的范围。出界,有龙。此外,< 8
比较不符合您的要求。
如果要检查边界,则应在访问或分配该部分数组之前执行此操作。
例如:
while(countM < 9){
if (countM > 7)
{
// do whatever you want when this should happen
break;
}
// rest of code
}
但正如你所看到的,这有点奇怪。你知道你会触发那个代码。
你可以用类似的东西做得更好
int val;
int countM = 0;
while (scanf("%d", &val) == 1)
{
if (countM > 7)
{
printf("Whoops");
// whatever you want
exit(1);
}
// rest of code
}