【问题标题】:Search for word within file and display the title of the section containing the word?在文件中搜索单词并显示包含该单词的部分的标题?
【发布时间】:2020-07-01 15:54:39
【问题描述】:

我必须从包含多首歌曲的文件中搜索一个单词,用特定的字符串分隔,并显示歌词中包含该单词的每首歌曲标题。

文件格式如下:

xxxxxxxxxx

song title

Lyrics

xxxxxxxxxx

Song Title

Lyrics

[...]

我写的代码是:

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

/* Note: pif will be function needed to search a word within a generic string */


int main(){
  FILE *fp=fopen("file.txt", "r");
  char line[200],search_string[]="xxxxxxxxxx",word[20],buff[200];
  int cnt=0,flag=0;
  gets(word);
  if (!fp)
    return -1;
  printf("\n\tSongs Containing %s: ", word);
  cnt=0;
  while ( fgets ( line, 200, fp ) != NULL ) /*read a line*/
  {
    if(strstr(line,search_string)){ /*find the separator*/
      fgets(line,200,fp);/*go ahead reading*/
      strcpy(buff,line); /*save the title, which is the very next line after the separator*/
      while(!strstr(line,search_string)){ /* while the lyrics do not match with another 
                                             separator go ahead reading*/
        fgets(line,200,fp);
        if(pif(line,word)) /*using the defined *pif* function (required), I'd find *word* 
                             within the line */
           flag=1;
      }
      if(flag)
         printf("%s", buff);
     
    }
  }
  fclose(fp);

  return 1;
}

无论如何我可以让这一切工作吗?输出显示每首歌曲的标题,而不是特定的。

【问题讨论】:

  • 欢迎来到 SO。 minimal reproducible example 还将包含一个最小输入示例,而不是其布局的伪代码。我们应该能够从您的帖子中剪切和粘贴并复制您的问题,而不必猜测发生了什么。请edit你的帖子。
  • 从不使用gets。它甚至不再是语言。

标签: c string file word


【解决方案1】:

if(flag) printf("%s", buff); break; 这应该在打印第一首歌曲后中断,但你说它不是......所以我认为你在帖子中打错了......

现在您的代码.. 在找到匹配项后将标志设置为 1 后,即使在打印字符串后也不会将其设置回零。当您的内心循环遍历整首歌曲时,打印在下一首歌曲的开头完成,您应该设置flag=0;,否则即使该单词不在歌曲中,因为标志保持为1,歌曲名称将被打印.

      if(flag)
      {
         printf("%s", buff);
         flag=0;
      }

这应该可行。

注意:所有这些都假设您的 pif 函数工作正常。

【讨论】:

    【解决方案2】:

    这只是在下次检查之前不将标志设为 0 的问题。现在,将打印第一首具有匹配世界的歌曲之后出现的每个标题。如果您的问题仍然存在,则可能与 pif 函数有关。如果你没有做对,请分享!

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 1970-01-01
      • 2013-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-30
      • 2022-07-25
      • 1970-01-01
      相关资源
      最近更新 更多