需要从stdin读取未确定数量的整数到数组中

所以我正在编写一个练习程序,它将整数作为stdin的输入,将它们加载到一个数组中,对数组进行排序,然后输出结果。

我一直在努力弄清楚C中IO的工作原理。 这是我到目前为止的情况,如果您发现任何问题/有任何建议,请告诉我。 理想情况下,我想避免使用缓冲区,但我似乎无法找到另一种方法来允许可变大小的输入

输入格式:“10 20 30 11 666 1 235”……等

// check if an input file is specified // If one is specified, then sort those numbers, otherwise pull from stdin if(inputFile == "stdin"){ // Load stdin into a buffer char buffer[100]; if(fgets(buffer, sizeof(buffer), stdin) == NULL) { Handle_EOForIOError(); } // Get a count of the numbers to create the array int numIntegers = 0; int num; while(sscanf(&buffer[0], "%d ", &num) == 1){ numIntegers++; } // Initialize the array with the proper size numbers = (int*)malloc(numIntegers*sizeof(int)); // Load the integers into the array int i = 0; while(sscanf(&buffer[0], "%d ", &numbers[i]) == 1){ i++; } } 

问题是sscanf没有将指针保留在缓冲区中。 所以每次代码调用sscanf它只是从缓冲区中获取第一个数字。 结果是无限循环。

要解决此问题,可以使用%n转换说明符。 %n返回转换使用的字符数。 该数字(我在下面的代码中称为delta )可用于将索引更新到缓冲区中。 以下是它的工作原理,每次调用sscanf返回一个delta 。 该delta被添加到indexindex在表达式&buffer[index]用于指向&buffer[index]中的下一个数字。

这是生成的代码的样子

 // Load stdin into a buffer char buffer[100]; if(fgets(buffer, sizeof(buffer), stdin) == NULL) Handle_EOForIOError(); // Get a count of the numbers to create the array int numIntegers = 0; int index = 0; int num, delta; while(sscanf(&buffer[index], "%d%n", &num, &delta) == 1) { numIntegers++; index += delta; } // Initialize the array with the proper size int *numbers = malloc(numIntegers*sizeof(int)); // Load the integers into the array index = 0; for ( int i = 0; i < numIntegers; i++ ) { if (sscanf(&buffer[index], "%d%n", &numbers[i], &delta) != 1) ComplainBitterlyAndExit(); index += delta; }