-2

我正在尝试从 txt 文件中获取每个单词,然后将其放入数组中。我的代码从文件中提取每个单词并将其保存为字符串没有问题。但是,当我尝试将字符串放入一个数组并打印出来时,只打印出最后几行,它都被扭曲了。

这是我的代码:

  typedef char * string;
  string strings[100];
  FILE* file = fopen(argv[1], "r");
  char line[256];

  while(fgets(line, sizeof(line), file))
  {
    string tmp = strtok(line, " ,'.-");

    while(tmp != NULL)
    {
      strings[count]= tmp;
      tmp = strtok(NULL, " ,.'-;");
      count++;
    }
  }

  int c2 = 0;

  while(strings[c2] != NULL)
  {
    printf("%s, ", strings[c2]);
    c2++;
  }

  return 0;
}

这是我正在阅读的文件中的文本:

人行道尽头有一个地方
在街道开始之前,
那里的草变得柔软而洁白,
太阳在那里燃烧着深红色的光芒,
那里的月鸟从他的飞行中休息
在薄荷风中冷却。
4

1 回答 1

1

几个明显的问题:

strings[count]= tmp;

This is just a pointer assignment. And tmp has the same value each time you make the assignment. You need to allocate a new string each time round the loop. And use strcpy to copy it.

Secondly your print loop assumes that the strings array is initialised with null pointers. It is not. You did not initialise it at all.

于 2013-03-29T23:36:14.803 回答