Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用strtok只给我每行的第一个单词?_C_Arrays_Struct_Strtok - Fatal编程技术网

C 使用strtok只给我每行的第一个单词?

C 使用strtok只给我每行的第一个单词?,c,arrays,struct,strtok,C,Arrays,Struct,Strtok,我的代码如下。我正在使用一个struct并接收一个输入文本文件。我把它分成几行,然后试着把每一行分成单独的单词。使用strtok,它目前只打印每行的第一个字。我怎样才能解决这个问题 typedef struct { char linewords[101]; char separateword[101]; } line; 主要内容如下: line linenum[101]; char var[101] char *strtok(char *str, const char deli

我的代码如下。我正在使用一个struct并接收一个输入文本文件。我把它分成几行,然后试着把每一行分成单独的单词。使用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]返回第一个单词,以此类推。这可能吗?或者有没有其他方法将我的输入拆分成文字

谢谢

#包括
#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;
}
#包括 类型定义结构{ 字符行字[101]; char*separateword[51]; }线路; 内部主(空){ 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); 代币 令牌=strtok(空,delm)){ linenum[i].separateword[j++]=token; } linenum[i++].separateword[j]=NULL; } {//测试打印 字符**p=linenum[0]。分隔符; 而(*p) puts(*p++); } 返回0; }
第二次调用必须使用
NULL
@Pavel这是否意味着在当前strtok行之后我应该添加'strtok(NULL,”?要获取字符串中的所有单词,需要反复调用
strok()
。有关示例,请参阅。@KittiCat:是的,请参阅NPE发布的链接或系统中有关strtok的文档。当它为你工作时,请考虑用固定代码提交答案,如果还没有一个。真是太棒了。出于好奇,这是将整行打印为一个单词:我可以将其拆分,以便将每个单词存储在linenum[I].separateword[j]的不同部分吗?也就是说,第一行的第一个单词可能类似于linenum[1]。separateword[0]?我很抱歉让您感到非常痛苦,但您能告诉我这是如何工作的吗?我读了几遍,有点糊涂了@KittiCat这个保存指针被strok剪切到行中单词的位置。@KittiCat:也许你需要在编译器中激活C99模式。。。e、 g.
gcc-std=c99
。如有必要,附在
{}
测试打印部件中。