问题:
我想制作一个 C 程序,它将一串以空格分隔的整数作为输入(正数和负数,可变位数)并将该字符串转换为一个 int 数组。
在 Stack Overflow 上还有一个关于从字符串输入中读取整数到数组的问题,但它不适用于数字长度超过 1 或负数的数字。
尝试:
#include <stdio.h>
int main () {
int arr[1000], length = 0, c;
while ((c = getchar()) != '\n') {
if (c != ' ') {
arr[length++] = c - '0';
}
}
printf("[");
for ( int i = 0; i < length-1; i++ ) {
printf("%d,", arr[i]);
}
printf("%d]\n", arr[length-1]);
}
如果我在终端中输入以下内容:
$ echo "21 7" | ./run
$ [2,1,7]
这是我得到的数组:[2,1,7] 而不是 [21,7]
如果我输入以下内容:
$ echo "-21 7" | ./run
$ [-3,2,1,7]
我得到:[-3,2,1,7] 而不是 [-21,7],这是没有意义的。
但是,如果我输入:
$ echo "1 2 3 4 5 6 7" | ./run
$ [1,2,3,4,5,6,7]
注意:我假设输入总是一串空格分隔的整数。
最佳答案
完整程序(改编自 this answer by @onemasse )(不再需要无效输入来停止读取输入):
#include <stdio.h>
#include <stdlib.h>
int main () {
int arr[1000], length = 0, c, bytesread;
char input[1000];
fgets(input, sizeof(input), stdin);
char* input1 = input;
while (sscanf(input1, "%d%n", &c, &bytesread) > 0) {
arr[length++] = c;
input1 += bytesread;
}
printf("[");
for ( int i = 0; i < length-1; i++ ) {
printf("%d,", arr[i]);
}
printf("%d]\n", arr[length-1]);
return 0;
}
来自 scanf
/sscanf
手册页:
These functions return the number of input items assigned. This can be fewer than provided for, or even zero, in the event of a matching failure.
因此,如果返回值为 0,则您知道它无法再进行转换。
示例 I/O:
$ ./parse
1 2 3 10 11 12 -2 -3 -12 -124
[1,2,3,10,11,12,-2,-3,-12,-124]
注意:我目前不确定这是如何工作的。我会仔细看看的。但是,如果有人理解,请编辑此帖子或发表评论。
关于C程序将空格分隔的输入字符串转换为int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760898/