我正在尝试从文件中获取 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/