gpt4 book ai didi

c - C 中的 fscanf() - 需要帮助使用指针表示法读取文件

转载 作者:行者123 更新时间:2023-11-30 17:08:17 24 4
gpt4 key购买 nike

花了一两个小时尝试调试这个,但无法弄清楚为什么它不能正确读取我的文件。

FILE *input;
int numAccounts = 7;
char **accountNames = malloc(sizeof(char)*numAccounts*10);
int *accountNumbers = malloc(sizeof(int)*numAccounts);
float *accountValues = malloc(sizeof(float)*numAccounts);
char *fileName = malloc(sizeof(char)*20);
input=fopen("input.txt","r");
int i;

for(i=0;i<numAccounts;i++) {
fscanf(input,"%s%d%f",*(accountNames+i),accountNumbers+i,accountValues+i);
printf("\n%s %d %f", *(accountNames+i), *(accountNumbers+i), *(accountValues+i));
}
fclose(input);
return 0;

这是 input.txt

Brown 1435 234.55
Dunn 2091 2011.75
Smith 8766 945.05
Stone 4530 0.0
Becker 9073 6235.75
Rich 1003 -42.00
Doe 6739 3655.80

谢谢!

最佳答案

您应该从非动态分配开始,

int main()
{
FILE *input = NULL;
int numAccounts = 7;

char accountNames[20] = "";
int accountNumbers = 0;
float accountValues = 0;

input=fopen("input.txt","r");
int i;

for(i=0;i<numAccounts;i++)
{
fscanf(input,"%s %d %f",accountNames,&accountNumbers,&accountValues);
printf("\n%s %d %f\n", accountNames, accountNumbers, accountValues);
}
fclose(input);
return 0;
}
<小时/>

如果您必须进行动态分配,那么这个指向字符的指针分配是不正确的:char **accountNames = malloc(sizeof(char)*numAccounts*10);

您需要首先分配 char *numAccounts,然后为每个 char * 分配 10 个字符。可以按如下方式完成:

    char **accountNames = malloc(sizeof(char*)*numAccounts);    // allocate numAccounts of char *
int i;
for( i=0; i < numAccounts; i++ )
{
*(accountNames + i) = malloc(sizeof(char)*10); // allocate 10 of char
}

所以这应该有效:

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

int main()
{
FILE *input = NULL;
int numAccounts = 7;

char **accountNames = malloc(sizeof(char*)*numAccounts); // allocate numAccounts of char *
int i;
for( i=0; i < numAccounts; i++ )
{
*(accountNames + i) = malloc(sizeof(char)*10); // allocate 10 of char
}
int *accountNumbers = malloc(sizeof(int)*numAccounts);
float *accountValues = malloc(sizeof(float)*numAccounts);

input=fopen("input.txt","r");
for(i=0; i<numAccounts; i++)
{
fscanf(input,"%s%d%f",*(accountNames+i), accountNumbers+i, accountValues+i);
printf("\n%s %d %f", *(accountNames+i), *(accountNumbers+i), *(accountValues+i));
}
fclose(input);
return 0;
}

关于c - C 中的 fscanf() - 需要帮助使用指针表示法读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729706/

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