簡體   English   中英

C將輸入文本文件解析為單詞

[英]C parsing input text file into words

我正在嘗試將輸入文件(包含具有多行和定界符的文本文檔,即“!,。?”)解析為單詞。 我的功能“拆分功能”是:

int splitInput(fp) {

    int i= 0;
    char  line[255];
    char *array[5000];
    int x;
    while (fgets(line, sizeof(line), fp) != NULL) {     
        array[i] = strtok(line, ",.!? \n");
        printf("Check print - word %i:%s:\n",i, array[i]);
        i++;
    }
    return 0;
}

這是更正后的函數[很抱歉,多余的樣式清理]:

int
splitInput(fp)
{
    int i = 0;
    char *cp;
    char *bp;
    char line[255];
    char *array[5000];
    int x;

    while (fgets(line, sizeof(line), fp) != NULL) {
        bp = line;
        while (1) {
            cp = strtok(bp, ",.!? \n");
            bp = NULL;

            if (cp == NULL)
                break;
            array[i++] = cp;

            printf("Check print - word %i:%s:\n",i-1, cp);
        }
    }

    return 0;
}

現在,看看strtok的手冊頁以了解bp技巧

如果我正確理解了您的問題,則希望閱讀每一行並將每一行拆分為單詞,然后將其添加到數組中。

    array[i] = strtok(line, ",.!? \n");

由於明顯的原因,這將無法工作,因為它將僅返回每行的第一個單詞,並且您從不分配內存。

這可能就是您想要的。

    char *pch;
    pch = strtok(line, ",.!? \n");
    while(pch != NULL) {
      array[i++] = strdup(pch); // put the content of pch into array at position i and increment i afterwards.
      pch = strtok(NULL, ",.!? \n"); // look for remaining words at the same line
    }

別忘了使用free數組元素。

暫無
暫無

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

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