我开始在类里面使用具有非常基础知识的结构,但我无法理解如何使用 strtok 从字符串复制到结构中的单词列表。到目前为止,这是我的代码,但是当我运行它时,我得到的只是段错误。之后我还想打印单词列表中的单词以及它们的长度。
#include <stdio.h>
#include <string.h>
struct myWord
{
char Word[21];
int Length;
} WordList[20];
int main(){
int i;
char myString[] = "the cat in the hat jumped over the lazy fox";
strcpy(WordList[0].Word, strtok(myString, " "));
WordList[0].Length = strlen(WordList[0].Word);
for(i=1; i<11; i++){
strcpy(WordList[i].Word, strtok(NULL, " "));
WordList[i].Length = strlen(WordList[i].Word);
}
for(i=0; i<11; i++){
printf("%s\n", WordList[i].Word);
}
}
最佳答案
可能这会是更好的解决方案:
#include <stdio.h>
#include <string.h>
struct myWord
{
char Word[21];
int Length;
} WordList[20];
int main(){
int i;
char myString[] = "the cat in the hat jumped over the lazy fox";
char *ptr;
ptr = strtok(myString, " ");
for(i=0; i<9 && ptr != NULL; i++){
ptr = strtok(NULL, " ");
strcpy(WordList[i].Word, ptr);
WordList[i].Length = strlen(WordList[i].Word);
}
for(i=0; i<11; i++){
printf("%s\n", WordList[i].Word);
}
}
关于从一串单词复制到 c 中的结构。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129880/