c - 从缓冲区读取整数到 C 中的数组

标签 c arrays buffer

所以我试图将从键盘读取的 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/

相关文章:

c++ - 重用 bindBufferBase 和 OpenGL 计算着色器

C 编码,比较浮点值时的意外行为

c - 查找结构数组中的记录数

c - C 中带有指针的缓冲区

c++ - NS3 : how to setup RcvBufSize for each TCP session?

c - perror() 和 printf() 之间的区别

ruby-on-rails - ruby 数组中的字符串替换

python - 多幅图像和一幅基本图像之间的欧氏距离

C 指针数组地址分配

C++ OpenGL Multithreading 与缓冲区资源