找不到空令牌的值代表空csv值时遇到问题

时间:2019-06-14 06:16:50

标签: c csv

因此,我想创建一个C程序,该程序将读取可能包含一些空值的csv文件。我需要我的程序将令牌设置为等于空值(如果有的话)。我写这段代码是因为strtok()只会忽略所有空值。

该程序通过获取该记录字符串并通过这些if检查将其分成3个标记来工作。

char record[100] = "1,,3,";

        char delimiter[] = ",";
        char *token1 = 0;
        char *token2 = 0;
        char *token3 = 0;



        static char *stringtobetokened = NULL;
        char *p= 0;
        stringtobetokened = record;

        if ((p = strpbrk(stringtobetokened, delimiter)) != NULL) {
            *p = 0;
            token1 = stringtobetokened;
            stringtobetokened = ++p;
            printf("token1's value:%s\n", token1);

        }

        if ((p = strpbrk(stringtobetokened, delimiter)) != NULL) {
            *p = 0;


            token2 = stringtobetokened;
            stringtobetokened = ++p;
            printf("token2's value:%s\n", token2);
            //this is where the issue is, this if check should be triggered since token2 is a empty value which should print the statement, token2 is null
            if (token2 == NULL)
            {
                printf("token2 is null\n");
                //insert some code that changes token2's value

            }

        }
        if ((p = strpbrk(stringtobetokened, delimiter)) != NULL) {
            *p = 0;
            token3 = stringtobetokened;
            stringtobetokened = ++p;
            printf("token3's value:%s\n", token3);

        }

我的问题是,尽管它确实识别出令牌2为空,但if支票

if (token2 == NULL)

不会触发。如果要触发检查,则需要此代码,以便可以在其中插入更改其值的代码。

如果令牌2不为null或'\ 0',那么它的值是什么?

这些是我运行代码时得到的结果:

token1's value:1
token2's value:
token3's value:3
Press any key to continue . . .

1 个答案:

答案 0 :(得分:1)

token2将指向empty字符串,因为您在先前的标记化过程中将,替换为0

                      token1 ----
                                 |
                               +---+---+---+-----
 stringtobetokened      =      | 1 | 0 | 0 |........
                               +---+---+---+-----
                                         |
                               token2 ----

用以下条件替换您的if支票。

 if (*token2 == '\0')