gpt4 book ai didi

c - 从文件读取并在c中存储多个数组

转载 作者:行者123 更新时间:2023-11-30 18:37:23 25 4
gpt4 key购买 nike

从文件中读取行时遇到问题

 int status,i=0;
FILE *fp;
fp=fopen("Accounts.txt","r+");
do
{
fscanf(fp,"%d",&ids[i]);
status=fscanf(fp,"%lf",&balances[i]);
fscanf(fp,"%ld",&phones[i]);
fscanf(fp,"%c",&types[i]);
i++;
}
while(status != -1 );

发生的情况是计数器 (i) 增加了 3 次,这很奇怪......所以想到将数组读取为不同的列,但如何做到这一点?编辑:这是文件中的输入数据115039312341212341

最佳答案

循环结构对于您想要完成的任务来说是有缺陷的。

假设输入文件只有一行数据。

1001 1234.99 12345678 C

fscanf 的所有调用都在循环的第一次迭代中成功。
i 递增。所以它的值现在是1

第一次调用 fscanf 无法在循环的第二次迭代中读取数据。对 fscanf 的其余调用也无法读取数据。
无论对 fscanf 的调用是否成功,您都会递增 i。现在,它的值为 2

因此,即使只有一行数据,当退出循环时,i 的值为 2

你需要使用类似的东西:

// Read all the data corresponding to an index.
// If there is an error in reading all of them, break out of the loop.
while ( fscanf(fp, "%d %lf %ld %c", &ids[i], &balances[i], &phones[i], &types[i]) == 4)
{
i++;
}

关于c - 从文件读取并在c中存储多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37257243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com