【问题标题】:How to store STDIN from text file如何从文本文件中存储 STDIN
【发布时间】:2019-10-27 02:19:34
【问题描述】:

我需要从文本文件中读取单词,然后计算每个单词的出现次数,但我不知道如何将单词存储在变量中。

我阅读了使用 fgets 的代码,然后我可以使用 printf 打印它。但是,当我尝试将字符数组存储在一个不同的数组中以供以后比较字符数组时,我不断收到段错误。如何将字符数组“行”保存在不同的数组中?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAXSIZE  500    
#define MAXWORDS 1000 


int main ( int argc, char *argv[] ) {
   char line[MAXSIZE];
   char line1[MAXWORDS][MAXSIZE];
   int i,j,k;
   int count = 0;


   while ( fgets ( line, MAXSIZE, stdin ) != NULL ) {
    printf("%s", line);


    strcpy(line1[count], line);

    printf("%s\n", line1[count][i]);


    count++;

   }

   return(0);
}

(这是我更新的代码,它仍然打印第一行,然后是段错误。)

当我编译并运行这段代码时,它会打印文本文件的第一行,然后返回“segmentation fault”

【问题讨论】:

  • 你永远不会初始化count。打开编译器警告并注意它们。还有……呃……你还没有了解strcpy()吗?
  • @Shawn,感谢您的回复,我发布了更新的代码
  • 如何“存储”STDIN...所以你想用你的二维数组作为你从stdin读取的所有内容的存储?很好,但是对于只包含'\n' 或类似"okay" 的文本的行的存储非常浪费。您还需要将尝试存储的行数限制为少于MAXSIZE 行。
  • 您是否要计算不同的单词?每行多个单词呢?

标签: c fgets


【解决方案1】:

也许问题代码很接近。

  #include <stdio.h>
  #include <string.h>
  #include <stdlib.h>

  #define MAXSIZE  500
  #define MAXWORDS 1000

  int main(int argc, char *argv[])
    {
    char line[MAXSIZE];
    char line1[MAXWORDS][MAXSIZE];
    int  count = 0;

    while(fgets(line, MAXSIZE, stdin))
      {
      printf("%s", line);
      strcpy(line1[count], line);
      printf("%s\n", line1[count]);  // instead of: printf("%s\n", line1[count][i]);

      count++;
      }

    return(0);
    }

【讨论】:

  • while (count &lt; MAXWORDS &amp;&amp; fgets(line, MAXSIZE, stdin)) 在复制到line1[count] 之前,您还应该将试用版'\n'line 中删除。使用line[strcspn (line, "\n")] = 0; 是一种简单可靠的方式。
【解决方案2】:

您的strcpy 可以正常工作,但printf 在编译时已引起警告,请将printf 行从printf("%s\n", line1[count]); 更改为printf("%s\n", line1[count]);

在 while 循环之后,您可以使用以下方法验证您的副本:

for (int i=0; i < count; i++){
    printf("%d: %s",i, line[i]);
}

虽然fgets 将在缓冲区末尾放置一个终止0-byte,但它对用户strncpy 更具防御性,保证不会复制超过n 字节,但在这个例子中你可以通过直接写入line[count] 缓冲区来完全消除副本。

在覆盖缓冲区之前,您应该小心并停止阅读。 当您调用fgets 时,您将读取限制为MAXSIZE,这很好,但您还应该检查计数是否低于MAXWORDS

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2020-10-18
    相关资源
    最近更新 更多