简体   繁体   English

将字符串和 integer 从文件读取到结构中 - C

[英]Reading string and integer from file into struct - C

I hope this question isn't too similar to another that's posted.我希望这个问题与发布的另一个问题不太相似。 I am still learning how to read other peoples code at this point let alone write my own.在这一点上,我仍在学习如何阅读其他人的代码,更不用说编写自己的代码了。 I am confused as to how to read both a string and int from a line in a file and store it in a struct called People.我对如何从文件中的一行读取字符串和 int 并将其存储在名为 People 的结构中感到困惑。 I have been looking at fgets, fscanf and even fread but I can't figure out what to use and where to use it.我一直在研究 fgets、fscanf 甚至 fread,但我不知道该使用什么以及在哪里使用它。 I am getting this data from a file with a max of 10 entries that looks like this:我从一个最多包含 10 个条目的文件中获取这些数据,如下所示:

Joshua 50
Dwayne 90
Jennifer 45
Goldilocks 85

Here is my code:这是我的代码:

typedef struct
{
    char *name[20];
    int change_amount;
    int fifties;
    int twenties;
    int tens;
    int fives;
}People;

int get_file()
{
    const int MAXPEOPLE = 10;
    People persons[MAXPEOPLE];
    int i = 0;
    FILE *fpointer;
    char line[12];
    fopen("file.txt", "r");
    if (fpointer == NULL)
    {
        perror("Error opening file");
        return (0);
    }
    while (fgets(line, 8, fpointer) != NULL)
    {
        //Max number of letters for name under assumption is 8
        char name[8];
        int amount = 0;
        scanf(line, "%s %d", name, amount);
        printf("%s", name);
        memset(line, 0, 8);
        for (int i = 0; i < MAXPEOPLE; ++i)
        {
            return(0);
        }
    }
}

Any help is appreciated.任何帮助表示赞赏。 Go easy on me:) Go 对我来说很容易:)

I think the main issue with getting the scanning right is that you read into line with fgets() (wise move) and then try to scan from there.我认为正确扫描的主要问题是您阅读与fgets()一致(明智之举),然后尝试从那里进行扫描。

scanf(line, "%s %d", name, amount);

but use the wrong function to do so.但使用错误的 function 这样做。 Use sscanf() .使用sscanf()
https://en.cppreference.com/w/c/io/fscanf https://en.cppreference.com/w/c/io/fscanf

For completeness let me add the contribution from comments by Martin James and Jonathan Leffler:为了完整起见,让我添加来自 Martin James 和 Jonathan Leffler 评论的贡献:

You only live twice, but you can only return once: your loop is pointless你只能活两次,但你只能返回一次:你的循环毫无意义

Ie once any iteration of your for loop has a return , and all of them have, your while loop is finished.即,一旦你的for循环的任何迭代都有一个return ,并且所有这些迭代都有,你的while循环就完成了。

You call fopen() but don't assign (or check) the returned value.您调用 fopen() 但不分配(或检查)返回值。 You then test the still uninitialized fpointer.然后测试仍未初始化的 fpointer。 Not a recipe for happiness!不是幸福的秘诀!

Ie this即这个

fopen("file.txt", "r");
if (fpointer == NULL)

should be应该

fpointer = fopen("file.txt", "r");
if (fpointer == NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM