所以我试图将从键盘读取的 int 值存储到 C 中的整数数组中。示例用户输入:
8 99 5 7 8
变量声明:
int k;
int size;
char buf[100];
上面是我的缓冲区和数组的其他变量。 下面是将整数读入缓冲区。
printf("Please enter in the numbers for the array:\n");
fgets(buf, 100, stdin);
buf[strlen(buf) - 1] = '\0';
size = (strlen(buf)/2)+1;
int *array = (int *)malloc(sizeof(int)*size);
这样就正确地分配了我的数组。
int i, j;
for(i = 0, j = 0; i < size; i++, j = j+2)
{
array[i] = buf[j] - '0';
}
上面的代码确实有效,但不适用于具有两位数的数字,仅适用于小于 10 和大于 0 的数字。如何修改我的代码以便正确读取整数?
我试图用 sscanf
做一个 for
循环,但这只会导致一个数组,所有元素中只输入第一个整数。
最佳答案
How can I fix my code so that I correctly read in the integers?
使用strtol()
按照@EOF 的建议解析字符串.它在它停止的地方提供了一个结束指针。
long *array = malloc(sizeof *array * size);
if (array == NULL) Handle_OutOfMemory();
char *p = buf;
size_t i;
for(i = 0; i<size; i++) {
// Cope with white space with nothing after it.
while (isspace((unsigned char) *p)) p++;
if (*p == '\0') break;
char *end;
errno = 0;
long num = strtol(p, &end, 10);
// If no conversion or out of range ...
if (p == end || errno) {
fprintf(stderr, "trouble converting `%s` into an integer.\n", p);
break;
}
array[i] = num;
p = end;
}
// Use array[0] ... array[i-1]
关于c - 从缓冲区读取整数到 C 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025219/