-2

我有以下 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

我的想法是逐行读取文件,并在找到字符串射手时使用 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

它不会让我得到射手的篮板。

4

2 回答 2

3
if (line1)
{
    while (fgets (line, sizeof line, file)!= NULL)
    fputs(line,stdout);
}

这是错误的,因为直到文件结尾fgets()才返回。NULL您要阅读直到遇到空行:

if (line1) {
    fgets(line, sizeof line, file);
    while (line[0] != '\n') {
        fputs(line, stdout);
        fgets(line, sizeof line, file);
    }
}
于 2013-07-09T11:56:29.457 回答
0

您的内部循环找到第一个 Shooter,然后打印文件的其余部分。

内部循环必须在第一个空行处停止。就像是:

而(线[0]!='\ n')
{
    输出...
    如果 ( fgets(...) == NULL )
        休息;
}

这在 EOF 条件下表现良好。

于 2013-07-09T12:01:31.613 回答