【问题标题】:Entering words from input file into array将输入文件中的单词输入数组
【发布时间】:2015-02-17 04:18:13
【问题描述】:

大家好,所以我正在尝试从输入文件中提取单词并与它们一起玩以将它们按特定顺序排列(我相信我做得正确)。

我的问题是,我认为实际上没有任何单词进入 words 数组,因为当我打印它时,什么都没有显示。如果我想从文件中取出单词并放入单词数组中。我做错了什么?

        while (fscanf(file, "%s", word) == 1)
        {
            wc = strtok(word, " \n");
            while (wc != NULL)
            {
                wc = strtok(NULL, " \n");
                count++;
            }

【问题讨论】:

  • 检查strcpy(word, words[x])这里words[x]未初始化
  • 你想在这里做什么wc = strtok(NULL, " \n");
  • 我只是想计算文件中的单词数,以便可以使用计数变量@Vagish

标签: c arrays file input


【解决方案1】:
while (fscanf(file, "%s", word) == 1)

我看到你正在使用fscanf()%s,所以基本上你只是从文件中获取一个单词,然后假设你已经获取了该行,你试图将这个单词分解为标记。

使用

char buf[100];
int count = 0;
while(fgets(buf, sizeof(buf),file) != NULL)
{
   // Break the line into words using space as delimiter and copy it to the words array
   char *p = strtok(buf," ");
   while(p != NULL)
   {
      // strcpy(words[count],p); If you wish to copy the words into an array
      count ++;
      p = strtok(NULL," ");
   } 
}
printf("Number of words in the file are %d\n",count);

【讨论】:

  • 以前是 %99s 我应该改回来还是试试这个?
  • @Jroc 还有多个错误。在获取每个令牌时,您需要将其复制到数组中,我认为您不会这样做
  • 那很可能是我的问题。我的思想在这一点上完全麻木了。所以我有点困惑如何解决这个@Gopi
  • @Jroc 检查编辑以计算文件中的单词数。需要添加多项检查以确保没有数组越界访问。我已经为您提供了如何完成此操作的大纲
猜你喜欢
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
  • 2015-07-11
相关资源
最近更新 更多