如何读取文件并将内容放入结构中(使用c)? [关闭]

问题描述 投票:0回答:1

我想要的是了解如何获取文件的内容并将它们放在结构中。

我正在使用的文件(用于测试目的)包含以下内容:

Pedro Nuno;10;15000,000000;2016;5;55;68;71;22

我想把它放在这个结构中:

typedef struct
{
    char *nome;
    int numero;
    float salario;
    int inicio_contrato;
    int anos_contrato;
    int forca_defesa;
    int forca_medio;
    int forca_avancado;
    int forca_guardaredes;
} jogadores;

我怎么去做呢?这些分号是必要的,还是应该删除它们?我对结构本身有任何重大问题吗?

我主要想回答第一个问题,但是,如果可能的话,我也希望你对我认为很重要的任何事情你的意见。

感谢您的时间。

c file struct
1个回答
1
投票

这是一个可能的解决方案,但是,我必须修改您的示例,以便使用点而不是逗号用于浮点数:

Pedro Nuno;10;15000.000000;2016;5;55;68;71;22

这是示例代码:

#include <stdio.h> // for input/output

#define BUFSIZE 1024
#define NAMESIZE 100

// this is your struct
typedef struct
{
    char *nome;
    int numero;
    float salario;
    int inicio_contrato;
    int anos_contrato;
    int forca_defesa;
    int forca_medio;
    int forca_avancado;
    int forca_guardaredes;
} jogadores;

int main()
{
    char buf[BUFSIZE], name[NAMESIZE], c;
    int i;

    // the name is handled seperately
    for (i = 0; (c = getchar()) != ';' && i < NAMESIZE - 1; i++) {
        name[i] = c;
    }
    name[i] = 0; // terminate the string

    // the rest of the line is read into a buffer
    for (i = 0; (c = getchar()) != EOF && i < BUFSIZE - 1; i++) {
        buf[i] = c;
    }
    buf[i] = 0; // terminate the string

    // the struct is created and the name is copied into the struct
    jogadores entry;
    entry.nome = name;

    // the numbers of the remaining line are read in
    sscanf(buf, "%d;%f;%d;%d;%d;%d;%d;%d;",
        &entry.numero, &entry.salario, &entry.inicio_contrato,
        &entry.anos_contrato, &entry.forca_defesa, &entry.forca_medio,
        &entry.forca_avancado, &entry.forca_guardaredes);

    // the whole struct is printed
    printf("%s\n%d\n%f\n%d\n%d\n%d\n%d\n%d\n%d\n",
        entry.nome, entry.numero, entry.salario, entry.inicio_contrato,
        entry.anos_contrato, entry.forca_defesa, entry.forca_medio,
        entry.forca_avancado, entry.forca_guardaredes);

    return 0; // tell the caller that everything went fine
}
© www.soinside.com 2019 - 2024. All rights reserved.