c - 使用 fscanf 接收数组

标签 c arrays scanf character-arrays

我正在尝试从文件中获取 float 的输入并将其排列到数组中。

唯一的问题是我不知道每次会有多少个 float ,尽管我知道 float 的最大数量是 1000。

我需要做的是让 fscanf 获取所有 float ,然后停在下一行,其中充满了整数。

这是我到目前为止本节的内容:

for (repetition = 0; repetition <= 1000; repetition++)
{ 

    fscanf(userFile, "%f", &itemPrice[itemNumber]);
    itemNumber++;

}

但不幸的是,这会继续将数组值分配给接下来几行中的所有其他值。

我发现了另一个用户输入,auctionItems并使用 while(itemNumber < auctionItems) 来控制数组长度

最佳答案

fscanf的返回值是成功读取的项目数。用它来决定何时停止。

#include <stdio.h>

int main(int argc,char * argv[])
{
  int i;
  float ff[1000];
  char next_text[17];

  for (i=0; i < 1000; i++) {
    int n_read;

    n_read = fscanf(stdin, " %f", &( ff[i] ));
    if (n_read < 1) {
      fscanf(stdin, "%16s", next_text);
      next_text[16] = (char) 0;
      printf("Next text: '%s'\n", next_text);
      break;
    }
  }

  printf("Read %d items, %f .. %f\n",i,ff[0],ff[i-1]);
  return 0;
}

关于c - 使用 fscanf 接收数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25858674/

相关文章:

java - 将文本字段值放入数组中,ArrayIndexOutOfBoundsException

arrays - Ruby,遍历变量名数组,将方法应用于每个并替换变量值

c - 如何访问 scanf 中最后读入的变量?

arrays - sscanf 多个格式说明符到单个数组

c - 在 C 中的 scanf 中使用定义(类型说明符)

c - 怎样才能释放token和aa指针呢?

c - 在调查中提取 winner/-s,然后打印

c - 关于 C 中的 malloc() 和 free()

c - 类型兼容性约定和函数声明

android - 从现有数组列表创建数组范围