次のbasket.txtファイルがあります
Center
defence=45
training=95
Shooter
points=34
Rebounds=7
Shooter
points=8
Rebounds=5
Forward
points=8
Rebounds=5
Shooter 値のみを取得して表示したい。このようなものを返すには:
Shooter
points=34
Rebounds=7
Shooter
points=8
Rebounds=5
私の考えは、ファイルを1行ずつ読み取り、文字列シューターが見つかったらstrstrを使用して、その上のすべてを印刷することです。しかし、次のコードで
int main()
{
static const char filename[] = "basket.txt";
FILE *file = fopen (filename, "r");
if (file!= NULL)
{
char line[128];
while (fgets (line, sizeof line, file)!= NULL)
{
char *line1 = strstr(line,"Shooter");
if (line1)
{
while (fgets (line, sizeof line, file)!= NULL)
fputs(line,stdout);
}
}
fclose(file);
}
else
{
perror(filename);
}
return 0;
}
それは私を返します
Shooter
points=34
Rebounds=7
Shooter
points=8
Rebounds=5
Forward
points=8
Rebounds=5
では、コードを変更して希望する結果を得るにはどうすればよいでしょうか?
アップデート
whileループを変更しました
while (fgets (line, sizeof line, file)!= NULL)
{
char *line1 = strstr(line,"Shooter");
if (line1)
{
fgets (line, sizeof line, file);
while (line[0] != '\n')
{
fputs(line,stdout);
fgets (line, sizeof line, file);
break;
}
しかし、結果は今
points=34
points=8
シューターズのリバウンドは返ってきません。