【问题标题】:C - Using strtok gives me only the first word of each line?C - 使用 strtok 只给我每行的第一个单词?
【发布时间】:2014-09-21 06:45:32
【问题描述】:

我的代码如下。我正在使用一个结构并接受一个输入文本文件。我将它分成几行,然后尝试将每一行分成单独的单词。使用 strtok,它目前只打印每行的第一个单词。我该如何解决这个问题?

typedef struct {
    char linewords[101];
    char separateword[101];
} line;

主要内容如下:

line linenum[101];
char var[101]
char *strtok(char *str, const char delim);

while fgets(linenum[i].linewords, 101, stdin) != NULL) {

    char* strcopy();
    char* strtok();
    strcpy(linenum[i].separateword,linenum[i].linewords);

    strtok(linenum[i].separateword, " "); /*line i'm referring to*/
    i++;
    }
}

对于任何混淆,我提前道歉。我想要的是这样 linenum[i].separateword[0] 将返回第一个单词等。这可能吗?还是有其他方法可以将我的输入拆分为单词?

谢谢

【问题讨论】:

  • 第二次调用必须使用NULL
  • @Pavel 这是否意味着在当前 strtok 行之后我应该添加 'strtok(NULL, " "); ?
  • 要获取字符串中的所有单词,需要反复调用strtok()。有关示例,请参见 tutorialspoint.com/c_standard_library/c_function_strtok.htm
  • @KittiCat:是的,请参阅 NPE 发布的链接或系统中 strtok 的文档。当它适合您时,如果还没有固定代码,请考虑提交带有固定代码的答案。
  • @NPE 谢谢!非常棒。只是出于好奇,这是将整行打印为一个单词:我可以将其拆分,以便每个单词存储在 linenum[i].separateword[j] 的不同部分吗?也就是说,第一行的第一个单词可以是 linenum[1].separateword[0]?

标签: c arrays struct strtok


【解决方案1】:
#include <stdio.h>
#include <string.h>

typedef struct {
    char linewords[101];
    char *separateword[51];
} line;

int main(void){
    line linenum[101];
    int i = 0;

    while(fgets(linenum[i].linewords, sizeof(linenum[i].linewords), stdin) != NULL) {
        char *token, *delm = " \t\n";
        int j = 0;
        for(token = strtok(linenum[i].linewords, delm);
            token;
            token = strtok(NULL, delm)){
            linenum[i].separateword[j++] = token;
        }
        linenum[i++].separateword[j] = NULL;
    }
    {//test print
        char **p = linenum[0].separateword;
        while(*p)
            puts(*p++);
    }
    return 0;
}

【讨论】:

  • 我很抱歉成为一个巨大的痛苦,但你能告诉我这是如何工作的吗?我读了几遍,有点困惑!
  • @KittiCat 这个保存指针被 strtok 剪切到了单词在行中的位置。
  • @KittiCat:也许您需要在编译器中激活 C99 模式...例如gcc -std=c99.
  • 如有必要,请附在{ }中的测试打印部分。
猜你喜欢
  • 1970-01-01
  • 2016-12-04
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2013-10-07
  • 2013-05-20
相关资源
最近更新 更多