c - 如何从字符串中读取可变数量的 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;
}
考虑到它是可变的并且之后仍然能够读取标题,我如何才能在一行中读取所有先前的任务编号?
解决方案
您还可以逐行扫描并将前两个数字分配给 id 和 duration,然后进行 int 分析并添加其余元素,nbPrev
直到遇到字母。
我不知道这是否是最好的方法,但我会这样做。
为什么不每次注册时也创建一个列表struct nbPrev
?
就像,不是nbPrev
type int
,而是 type list
?
推荐阅读
- javascript - JS将base64图片转为图片文件
- python - 如何将单个日期与 Flask、SQLAlchemy、SQLite 进行比较
- dialogflow-es - 我想将对话框流自定义有效负载响应显示为可单击的文本按钮(即单击时它应该返回具有相同文本的消息,与芯片相同)
- django - 将多个图像库添加到带有文本的页面?
- python - 每次都在 django 查询数据库中过滤查询集吗?
- c# - 数据层和业务层之间的持久层?
- flutter - Flutter 创建新数据库时将旧数据库中的所有表和数据复制到新数据库中
- c# - 将空值设置为列表中最接近的最后一个非空值 - LINQ
- javascript - Vuetify,动画 v-data-table tr
- python - Selenium Webdriver Python 不会通过 xpath 找到要单击的元素,尽管它存在于页面上