首页 > 解决方案 > 如何从字符串中读取可变数量的 int

问题描述

我有以下文本文件

0 0 0 debut
1 120 0 permis exploitation
2 180 1 1 piste 6km
3 3 1 2 installation sondeuses
4 30 1 2 batiments provisoires
5 60 1 2 groudronnage piste
6 90 1 4 adduction eau
7 240 2 3 4 campagne sondage
8 180 3 5 6 7 forage  3 puits
9 240 3 5 6 7 construction bureaux logements
10 30 2 8 9  transport installation matériel
11 360 2 8 9  traçage du fond
12 240 2 8 9 construction laverie
13 0 3 10 11 12 fin des travaux

每一行是一个任务的表示,描述如下:第一个数字是和ID,第二个是持续时间,第三个是之前需要的任务数,后面的所有数字都是需要的ID任务。最后,最后的字符串是字符串的标题。

我试图通过读取这个文件来填充这些结构的数组。这是结构:

typedef struct{
  int id; 
  int duration; 
  int nbPrev;     /* number of required previous tasks */
  int prev[NMAXPREV];  /*array of required previous tasks*/
  char title[LGMAX];   
}Task ;

这是我读取文件的代码

int readTasksFile(char* file_name, Task t[])
{
    FILE* f;
    char line[256] = {'\0'};
    int i = 0;
    char c[1] = {0};

    if((f = fopen(file_name, "r")) == NULL)
    {
        perror("The file couldn't be opened");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, 256, f) != EOF)
    {
        sscanf_s(line, "&d &d &d", &(t[i].id), &(t[i].duration), &(t[i].nbPrev));

        i++;
    }

    fclose(f);
    return 0;
}

考虑到它是可变的并且之后仍然能够读取标题,我如何才能在一行中读取所有先前的任务编号?

标签: cstringfile

解决方案


您还可以逐行扫描并将前两个数字分配给 id 和 duration,然后进行 int 分析并添加其余元素,nbPrev直到遇到字母。

我不知道这是否是最好的方法,但我会这样做。

为什么不每次注册时也创建一个列表struct nbPrev

就像,不是nbPrevtype int,而是 type list


推荐阅读