你的问题是scanf
当它查找下一个项目时,将自动跳过所有空白(空格、制表符、换行符)。您可以通过专门要求读取换行符来区分换行符和其他空格:
int main() {
int arr[30]; // results array
int cnt = 0; // number of results
while (1) {
// in the scanf format string below
// %1[\n] asks for a 1-character string containing a newline
char tmp[2]; // buffer for the newline
int res = scanf("%d%1[\n]", &arr[cnt], tmp);
if (res == 0) {
// did not even get the integer
// handle input error here
break;
}
if (res == 1) {
// got the integer, but no newline
// go on to read the next integer
++cnt;
}
if (res == 2) {
// got both the integer and newline
// all done, drop out
++cnt;
break;
}
}
printf("got %d integers\n", cnt);
return 0;
}
这种方法的问题在于,它只识别整数后面的换行符,并且会默默地跳过仅包含空格的行(并从下一行开始读取整数)。如果这是不可接受的,那么我认为最简单的解决方案是将整行读入缓冲区并解析该缓冲区中的整数:
int main() {
int arr[30]; // results array
int cnt = 0; // number of results
char buf[1000]; // buffer for the whole line
if (fgets(buf, sizeof(buf), stdin) == NULL) {
// handle input error here
} else {
int pos = 0; // current position in buffer
// in the scanf format string below
// %n asks for number of characters used by sscanf
int num;
while (sscanf(buf + pos, "%d%n", &arr[cnt], &num) == 1) {
pos += num; // advance position in buffer
cnt += 1; // advance position in results
}
// check here that all of the buffer has been used
// that is, that there was nothing else but integers on the line
}
printf("got %d integers\n", cnt);
return 0;
}
另请注意,当行上的整数超过 30 个时,上述两种解决方案都会覆盖结果数组。如果某些输入行比缓冲区适合的长度长,第二种解决方案也会留下一些未读的输入行。根据您的输入来自何处,这两个问题可能都需要在实际使用代码之前解决。