Во-первых, не используйте scanf
.Если stdin
не соответствует ожидаемому, он оставит его в буфере и просто перечитает тот же неправильный ввод.Это очень неприятно для отладки.
const int max_values = 10;
for (int i = 0; i <= max_values; i++) {
int value;
if( scanf("%d", &value) == 1 ) {
printf("Got %d\n", value);
}
else {
fprintf(stderr, "I don't recognize that as a number.\n");
}
}
Смотрите, что происходит, когда вы кормите его чем-то, что не является числом.Он просто пытается снова и снова читать плохую строку.
$ ./test
1
Got 1
2
Got 2
3
Got 3
foo
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
I don't recognize that as a number.
Вместо этого используйте fgets
, чтобы надежно прочитать всю строку, и sscanf
, чтобы проанализировать ее.%f
для поплавков, десятичных чисел.Используйте %d
для распознавания только целых чисел.Затем проверьте, является ли оно положительным.
#include <stdio.h>
int main() {
const size_t max_values = 10;
int values[max_values];
char buf[1024];
size_t i = 0;
while(
// Keep reading until we have enough values.
(i < max_values) &&
// Read the line, but stop if there's no more input.
(fgets(buf, sizeof(buf), stdin) != NULL)
) {
int value;
// Parse the line as an integer.
// If it doesn't parse, tell the user and skip to the next line.
if( sscanf(buf, "%d", &value) != 1 ) {
fprintf(stderr, "I don't recognize that as a number.\n");
continue;
}
// Check if it's a positive integer.
// If it isn't, tell the user and skip to the next line.
if( value < 0 ) {
fprintf(stderr, "Only positive integers, please.\n");
continue;
}
// We got this far, it must be a positive integer!
// Assign it and increment our position in the array.
values[i] = value;
i++;
}
// Print the array.
for( i = 0; i < max_values; i++ ) {
printf("%d\n", values[i]);
}
}
Обратите внимание, что поскольку пользователь может вводить неверные значения, мы не можем использовать простой цикл for.Вместо этого мы выполняем цикл до тех пор, пока либо не прочитаем достаточно действительных значений, либо больше не будет ввода.