gpt4 book ai didi

c - fscanf 只扫描我文件的第一个值

转载 作者:太空宇宙 更新时间:2023-11-04 03:41:24 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <stdlib.h>

struct account{
int accountId;
char *name;
double amount;
};
int main(int argc, char **argv)
{
FILE *file=fopen(argv[1],"r");
struct account *Ptr;
int i,j;
int size=0;

fscanf(file,"%d",&size);
if(size==0)
{
printf("Unable to open file");
return 0;
}
printf("%d",size);
Ptr=malloc(sizeof(struct account)*size);

for(i=0;i<size;i++)
{
fscanf(file,"%d%s%lf\n",&(Ptr+i)->accountId,(Ptr+i)->name,&(Ptr+i)->amount);
}

for(j=0;j<size;j++)
{
printf("%d%s%lf\n",((Ptr+j)->accountId),(Ptr+j)->name,((Ptr+j)->amount));
}

fclose(file);
free(Ptr);

return 0;

这个用来读入输入文件2个2 哈利 23.458 莎莉 100.91

不知何故,代码在 for 循环期间读取了前 2 个大小和第二个 2,但没有别的

最佳答案

您的代码有未定义的行为,因为您正在将数据读入未初始化的指针:

fscanf(file,"%d%s%lf\n",&(Ptr+i)->accountId,(Ptr+i)->name,&(Ptr+i)->amount);
// ^^^^
// This pointer is uninitialized ----------------------+

解决这个问题的三种方法:

  • 使 name 成为一个数组,而不是一个指针,例如字符名称[MAX_NAME],或者
  • 在将数据读入之前,使用mallocname 分配空间。
  • 读入临时缓冲区,然后 malloc 确切的字符数。

关于c - fscanf 只扫描我文件的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335255/

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