c - 如何使用 strtok 进行标记,无论该行中是否有字符串 - C

标签 c tokenize strtok

我正在尝试读取文件每一行的最后一个单词。当文件中的行看起来像 2011/1/29,,0 ,1063 时,我可以获得所需的结果,但当文件中的行看起来像 2011/1/29 时,我无法获得所需的结果,夏天,0 ,1063

我以为我正在标记每个“,”,因此该行中的字符串不应该影响我的结果,但它确实如此。有人知道为什么吗?

#include <stdio.h>
#include <string.h>
int main (){
    FILE* fp;
    char tmpline[256]; 
    char* separator2 =",";
    char* words;
    int i = 0; 

    fp = fopen("printer.txt", "r");
    while (fgets(tmpline, 256, fp) != NULL){

        printf(tmpline);
        if (tmpline != NULL){ 
            words = strtok(tmpline,separator2); //get first token 
            while (words != NULL) { /* walk through other tokens */
                for (i=0; i<3; i++) { 
                    if (i==2) {
                        printf( "papers: %s\n",words);                      
                    }
                    words= strtok(NULL, separator2);
                }
            }
        }
    }

fclose (fp);
    return 0;
}

这是输出的一部分

// 2011/1/29,,0 ,1063
// papers: 1063

// 2011/1/31,,2 ,991
// papers: 991

// 2011/2/1,,3 ,1789
// papers: 1789

// 2011/2/2,spring,4 ,974
// papers: 4 
// papers: (null)
// 2011/2/3,spring,5 ,1119
// papers: 5 
// papers: (null)
// 2011/2/4,spring,6 ,617

最佳答案

这将存储指向每个有效 token 的指针。当您没有更多 token 时,请使用存储的 token 。我还添加了更多分隔符,以包含空格,原因之一是 fgets 保留了文件中的 newline

#include <stdio.h>
#include <string.h>

int main (void){                                // correct signature
    FILE* fp;
    char tmpline[256]; 
    char* separator2 =", \t\r\n";               // added more delimiters
    char* words;
    char *lastword;                             // previous valid token

    fp = fopen("printer.txt", "r");
    while (fgets(tmpline, 256, fp) != NULL) {
        lastword = NULL;
        words = strtok(tmpline,separator2);     // get first token 
        while (words != NULL) {                 // walk through other tokens
            lastword = words;                   // remeber previous token
            words= strtok(NULL, separator2);    // get next token
            }
        if(lastword != NULL) {
            printf( "papers: %s\n", lastword);                      
        }
    }

    fclose (fp);
    return 0;
}

关于c - 如何使用 strtok 进行标记,无论该行中是否有字符串 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37663048/

相关文章:

c - RUN FAILED 退出值 -1 073 741 819 - 我的代码有什么问题?

c - 读取 float 的最小缓冲区长度

html - sqlite-fts3 : custom tokenizer?

c++ - 用于引号和括号的 Boost.Tokenizer

c - C 中的字符串标记

c - 在 C (Linux) 中查找虚拟网络接口(interface)

c - 为什么在更改 main 的签名时会出现段错误?

c - 打印字符串中的中间单词。 C编程

c - 使用strtok在c中分割一个字符串

c - 在c中的函数中使用 token (strtok)的值