fscanf只扫描我文件的第一个值 #包括 #包括 结构帐户{ 国际帐户ID; 字符*名称; 双倍金额; }; int main(int argc,字符**argv) { FILE*FILE=fopen(argv[1],“r”); 结构账户*Ptr; int i,j; int size=0; fscanf(文件“%d”,大小(&S); 如果(大小==0) { printf(“无法打开文件”); 返回0; } printf(“%d”,大小); Ptr=malloc(sizeof(结构账户)*大小); 对于(i=0;iaccountId,(Ptr+i)->名称和(Ptr+i)->金额); } 对于(j=0;jaccountId),(Ptr+j)->名称,((Ptr+j)->金额); } fclose(文件); 免费(Ptr); 返回0;
} 这用于读取输入文件 2. 2.23.45 8莎莉100.91fscanf只扫描我文件的第一个值 #包括 #包括 结构帐户{ 国际帐户ID; 字符*名称; 双倍金额; }; int main(int argc,字符**argv) { FILE*FILE=fopen(argv[1],“r”); 结构账户*Ptr; int i,j; int size=0; fscanf(文件“%d”,大小(&S); 如果(大小==0) { printf(“无法打开文件”); 返回0; } printf(“%d”,大小); Ptr=malloc(sizeof(结构账户)*大小); 对于(i=0;iaccountId,(Ptr+i)->名称和(Ptr+i)->金额); } 对于(j=0;jaccountId),(Ptr+j)->名称,((Ptr+j)->金额); } fclose(文件); 免费(Ptr); 返回0;,c,C,} 这用于读取输入文件 2. 2.23.45 8莎莉100.91 在for循环过程中,代码以某种方式读取前2个for size和第2个for size,但除此之外没有任何内容您的代码具有未定义的行为,因为您正在将数据读入未初始化的指针: #include <stdio.h> #include <stdlib.h> struct account{ int accountId; char *name; double amount; }; int main(int argc,
在for循环过程中,代码以某种方式读取前2个for size和第2个for size,但除此之外没有任何内容您的代码具有未定义的行为,因为您正在将数据读入未初始化的指针:
#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;
有三种方法可以解决这一问题:
- 将
设置为数组,而不是指针,例如name
,或char name[MAX\u name]
- 在读取数据之前,使用
为malloc
分配空间name
- 读入一个临时缓冲区,然后
确切的字符数malloc
scanf()格式字符串中不需要空格。
。所有scanf()
说明符,除了“%c”
<代码>%n“<代码>“%[”使用前导空格。添加空格可能看起来更好,但不会更改此代码的功能。因此,我需要在主函数中对其进行malloc处理?@BrandonTomblinson这是一种方法。使用数组将是另一种有效方法。它必须采用指针格式,因此,例如,我必须更改代码toname=malloc(sizeof(char)*10);sizeof(char)
标准要求在所有实现中都是1
,因此对于九个字符的名称(还有一个是空终止符),它只是malloc(10)
。
fscanf(file,"%d%s%lf\n",&(Ptr+i)->accountId,(Ptr+i)->name,&(Ptr+i)->amount);
// ^^^^
// This pointer is uninitialized ----------------------+