【发布时间】: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。它甚至不再是语言。