我需要编写代码,要求您输入介于3-69之间的数字。如果输入不正确,我必须在stderr中打印"wrong input"
(如果是字母)或"out of range"
(如果它不属于该间隔)。
我可以处理"out of range"
stderr,但不能处理另一个。当我输入一个字母时,它会自动转换为一个大数字,这是我认为内存中的某个地址。在这种情况下,stderr变为"out of range"
,而不是"wrong input"
。有没有办法解决?
[将变量引入int也许是错误的?(这些是获取输入的代码行:]
int x, y;
scanf("%i %i",&x,&y);
当我输入一个字母时,它会自动转换为一个大数字,这是我认为内存中的地址或其他内容。
[x
和y
中都是垃圾。
scanf("%i %i",&x,&y);
表示要查找两个整数。如果scanf
没有看到两个整数,它将失败并且不会向x
或y
写任何内容。因为您没有检查scanf
是否成功,所以当您读取x
和y
时,它们将被初始化。它们将包含当时内存中的所有垃圾。
天真的方法是首先检查scanf
是否成功。然后检查数字是否在正确的范围内。为了说明起见,我将问题简化为一个数字。
#include <stdio.h>
int main() {
int num;
while(1) {
if( scanf("%i ",&num) != 1 ) {
fprintf(stderr, "Please enter a number.\n");
continue;
}
if( num < 3 || 69 < num ) {
fprintf(stderr, "The number must be between 3 and 69.\n");
continue;
}
break;
}
printf("Your number is %i.\n", num);
}
但是当用户输入“ a”时,将进入无限循环。
$ ./test
a
Please enter a number.
Please enter a number.
Please enter a number.
scanf
失败时,它将用户输入保留在stdin
上。上面的程序将反复读取相同的a
。这是scanf
的一个普遍问题,它是为结构合理的输入而设计的,而用户输入的结构却不合理。参见the C FAQ for more problems with scanf。
相反,请分别阅读和分析。用fgets
读整行,用sscanf
解析,如果不是您要读的另一行。
#include <stdio.h>
int main() {
int num;
char line[1024];
while(fgets(line, sizeof(line), stdin)) {
if( sscanf(line, "%i ",&num) != 1 ) {
fprintf(stderr, "Please enter a number.\n");
continue;
}
if( num < 3 || 69 < num ) {
fprintf(stderr, "The number must be between 3 and 69.\n");
continue;
}
break;
}
printf("Your number is %i.\n", num);
}