簡體   English   中英

如何使用 strtok 獲取令牌內的令牌?

[英]How to use strtok to get tokens within tokens?

我試圖從文件的每一行中分離令牌並打印它們。 我使用的 delim 是“,”。 但是,某些行的最后一個字符串在字符串中包含帶有“,”的標記。 如何獲取帶有“,”的整個字符串?

char *buff = (char*)malloc(sizeof(char)*256);
char *tmp;

while (fgets(buff, 256, FILENAME) != NULL) {
    tmp = strtok(buff, ",");
    printf("%s\n",tmp);

    tmp = strtok(NULL, ",");
    printf("%s\n",tmp);

    tmp = strtok(NULL, ",");
    printf("%s\n",tmp);
    
}

輸入文件中的行如下所示:

This,is,a
Code,in,"c,language"
rat, mouse, "rat, mouse"

我試圖有這樣的輸出:

This
is
a
Code
in
c, language
rat
mouse
rat, mouse

因為空閑的星期天是進行簡單編碼的好時機,所以這是我在短時間內編寫的解析器。 它不解析轉義序列並且幾乎沒有錯誤處理,但可以幫助您入門。

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

void parse(FILE *file) {
    int c;
    // keep track if we are in quotes or not
    bool inquote = false;
    // keep track if the field started or not
    bool infield = false;
    
    while ((c = fgetc(file)) != EOF) {

        if (!infield) {
            // ignore leading spaces before fields
            if (c == ' ') continue;
            infield = true;
        }

        switch(c) {
        case '"':
            inquote = !inquote;
            continue;
        case ',':
            // if comma is in quotes, just print it
            if (inquote) break;
            // fallthrough
        case '\n':
            // comma or newline are field separators
            printf("\n");
            infield = false;
            continue;
        }
        // output the character
        printf("%c", c);
    }
}

int main() {
    parse(stdin);
    return 0;
}

它在 Godbolt 上輸出

This
is
a
Code
in
c,language
rat
mouse
rat, mouse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM