检查strtok中是否存在令牌

时间:2018-11-22 02:50:14

标签: c io token strtok

我需要修改一些当前从ascii文件读取两列数据的C代码,以便它可以检查是否提供了第三列,如果找到了第三列,则将读取第三列。

相关代码段当前为:

    struct forestListElement * forestList = malloc(nTrees*sizeof(struct forestListElement));
    // skip first line                                                                                                                                                      
    fgets(line,800,file);
    cnt = 0;
    while( fgets(line,sizeof(line),file) !=NULL)  {
            pch = strtok(line," ");
            forestList[cnt].treeRootId =atoll(pch);
            pch = strtok(NULL," ");
            forestList[cnt].forestId = atoll(pch);
            cnt++;
    }

此代码段循环遍历当前具有两列数据(长格式的两个ID)的文件。但是我想修改代码,以便在读取前两列后检查是否存在第三列,如果存在,则从该列读取权重。如果第三列不存在,则将权重设置为1。我想将代码修改为:

    struct forestListElement * forestList = malloc(nTrees*sizeof(struct forestListElement));
    // skip first line                                                                                                                                                      
    fgets(line,800,file);
    cnt = 0;
    while( fgets(line,sizeof(line),file) !=NULL)  {
            pch = strtok(line," ");
            forestList[cnt].treeRootId =atoll(pch);
            pch = strtok(NULL," ");
            forestList[cnt].forestId = atoll(pch);
            forestList[cnt].forestWeight = 1.0;
            if(<check if third column exists>){   \\ <-- what do I put here? 
                  pch = strtok(NULL," ");
                  forestList[cnt].forestWeight = atof(pch);
            }
            cnt++;
    }

我需要在if语句中包括什么?

很抱歉,如果这很简单,但是我对C不熟悉,并且正在努力寻找要在Google上搜索的内容!

谢谢。

0 个答案:

没有答案
相关问题