【问题标题】:Reading words in line and putting them in array逐行读取单词并将它们放入数组中
【发布时间】:2013-10-29 17:30:05
【问题描述】:

我需要我的程序读取文件的一行,然后解析该行并将任何单词插入每个数组的索引中。唯一的问题是我不知道每行有多少字,每行可以有1-6个字。

这就是一个简单文件的样子:

苹果橙

电脑终端键盘鼠标

如果我正在扫描第 1 行,我需要一个 char 数组来保存单词 apple 和 oranges。 示例:

words[0][0] = "apple";
words[1][0] = "oranges";

到目前为止,我有这样的东西,但我怎样才能让它每行少于 6 个单词?

fscanf(file, "%19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ] %19[^ ]", string1, string2, string3, string4, string5, string6);

【问题讨论】:

  • 为什么不阅读整行?并使用空格分隔符分割?

标签: c scanf


【解决方案1】:

您正在阅读整个文件,而不是一行。

你可以这样做:

char line [128];
char *pch;
char words[6][20]; // 6 words, 20 characters 
int x;

while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
      {
         pch = strtok (line," ,.-");
         while (pch != NULL)
         {
            strcpy(words[x], pch);
            pch = strtok (NULL, " ,.-");
         }
         x++;

        /*
           At this point, the array "words" has all the words in the line
         */

      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 2023-01-17
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多