目前我正在使用此功能:
void manually(int *data, int size){
int i;
printf("Enter numbers of the array:\n");
if(data != NULL){
for(i = 0; i < size; i++){
if ((scanf("%d", &data[i]) == 1) && (getchar() == '\n') && (data[i] > 0)){
printf("Number: %d entered\n", data[i]);
} else {
printf("Invalid input\n");
// while(getchar() != '\n');
i = i - 1;
}
}
} else {
printf("Memory wasn't allocated\n");
}
}
但是,输入其他符号而不是数字时,它不起作用。我认为fgets()将是解决方案,但不知道我应该如何修改它。我是C的新人,绝对新手。感谢。
答案 0 :(得分:-1)
当输入无效输入时,您必须刷新标准输入stdin
,否则对scanf
的后续调用将获得相同的无效输入,并且您将以无限循环结束。
执行此操作的一种方法是调用
fseek(stdin,0,SEEK_END);
有些人警告说这可能无法移植(在fseek
上使用stdin
)。
另一种方法是在到达换行符之前调用getchar()
:
while( getchar() != '\n' );
就像你评论的那条线一样。
所以整个事情变成了:
void manually(int *data, int size){
int i;
printf("Enter numbers of the array:\n");
if(data != NULL){
for(i = 0; i < size; i++){
if ((scanf("%d", &data[i]) == 1) && (data[i] > 0)){
printf("Number: %d entered\n", data[i]);
} else {
printf("Invalid input\n");
while( getchar() != '\n' );
i = i - 1;
}
}
} else {
printf("Memory wasn't allocated\n");
}
}
请注意,您不需要
(getchar() == '\n')
进入if
声明