Нет ошибки, ваш while
l oop будет go до тех пор, пока не будет введен недопустимый ввод, у вас нет ограничения на количество вводов, поэтому он будет продолжать принимать значения, что впоследствии может стать проблемой поскольку в вашем контейнере есть место только для 100 int
s.
Он останавливается на некоторых онлайн-компиляторах из-за того, как они используют stdin
входы, это в основном одноразовое считывание.
Примеры:
Он останавливается здесь , имеет один раз stdin
считывание.
Не останавливается здесь , имеет консоль типа ввода / вывода.
Итак, если вы хотите остановиться на заданном количестве входов, вы можете сделать что-то вроде:
//...
while (i < 5 && scanf(" %d", &array[i]) > 0)
{
i++;
}
//...
Это будет 5 int
s, выйдите из l oop и перейдите к следующему оператору.
Если вы действительно не знаете количество входов, вы можете сделать что-то вроде:
//...
while (i < 100 && scanf("%d", &array[i]) > 0) { // still need to limit the input to the
// size of the container, in this case 100
i++;
if (getchar() == '\n') { // if the character is a newline break te cycle
// note that there cannot be spaces after the last number
break;
}
}
//...
В предыдущей версии нет некоторые проверки ошибок, поэтому для более комплексного подхода вы можете сделать следующее:
#include <stdio.h>
#include <string.h> // strcspn
#include <stdlib.h> // strtol
#include <errno.h> // errno
#include <limits.h> // INT_MAX
int main() {
char buf[1200]; // to hold the max number of ints
int array[100];
char *ptr; // to iterate through the string
char *endptr; // for strtol, points to the next char after parsed value
long temp; //to hold temporarily the parsed value
int i = 0;
if (!fgets(buf, sizeof(buf), stdin)) { //check input errors
fprintf(stderr, "Input error");
}
ptr = buf; // assing pointer to the beginning of the char array
while (i < 100 && (temp = strtol(ptr, &endptr, 10)) && temp <= INT_MAX
&& errno != ERANGE && (*endptr == ' ' || *endptr == '\n')) {
array[i++] = temp; //if value passes checks add to array
ptr += strcspn(ptr, " ") + 1; // jump to next number
}
for (int j = 0; j < i; j++) { //print the array
printf("%d ", array[j]);
}
return EXIT_SUCCESS;
}