从一串单词复制到 c 中的结构。

标签 c structure

我开始在类里面使用具有非常基础知识的结构,但我无法理解如何使用 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/

相关文章:

Python ctypes - 访问 Structure.value 中的数据字符串失败

c++ - SendMessage(hwnd, registeredmssghere, 0, 1) 收到但未被发送到的 Hook 线程正确识别!

c - 多个if条件优化

c - 它的输出是什么?为什么?

c - 如何在c程序中避免 "Segmentation Fault"

c - 无法从 C 中的结构中打印字段

matlab - 如何将 1 个结构字段保存到另一个已保存的结构及其字段中

c - 如何唤醒正在 sleep (3)的线程

C - 跨多个文件返回结构指针时出错

java - 如果我的 java 测试资源比较大(超过 100MB),我应该把它们放在哪里?