使用getline和>>读取文件C ++时 [英] Use getline and >> when read file C++

查看:70
本文介绍了使用getline和>>读取文件C ++时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为文件中的数据如下所示:第1行是名称(第一名),下一行是分数(score1分数2 .... score5),依此类推...所以我认为我需要getline作为名称和>>得分

Because data from file look like this: line 1 is name (first last), next line is score (score1 score 2 ....score5) and so on... So I think that I need getline for name and >> for score

数据文件示例

David Beckham
80 90 100 20 50
Ronaldinho Gaucho
99 80 100 20 60
....

首先,我具有结构

struct Player {
string name;
int score[5];
} player[size]

从文件中读取数据时

int i = 0;
while(!file.eof())
    {
        for (int j = 0; j < 2; j++) //read each 2 two lines
        {               
            if(j==0) // name
            {               
                getline(file, player[i].name);  
            }
                        else if(j==1) // score
            {
                for(int k=0; k<5; k++) file >> player[i].grade[k];
            }
                }
         i++; //move to next player
    }

问题是在读取所有分数之后(第一位玩家的),看来好像没有转到下一行继续读取下一个名字,有点乱七八糟。因此,有任何建议纠正我的代码或执行此操作的新想法吗?

Problem is after read all scores (of first player), it seems like doesn't go to next line to continue read next name, kind of mess up there. So any suggestions to correct my code or new idea to do this?

推荐答案

在阅读了最后一个分数之后,换行符仍然坐在输入缓冲区上。您需要跳过。 ignore 函数对此非常有用

After reading the last score, the line break is still sitting on the input buffer. You need to skip that. The ignore function is useful for that.

getline(file, player[i].name);
for (int k = 0; k < 5; ++k)
  file >> player[i].grade[k];
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

根据需要检查错误。 >> 运算符, getline ignore 全部返回流引用,您可以检查流引用是否成功。

Check for errors as appropriate. The >> operator, getline, and ignore all return the stream reference, which you can check for success or failure.

不需要$ j 循环,因为每次迭代都做完全不同的事情。只需立即编写 j = 0 例,然后写一个 j = 1 例,然后摆脱循环,就像我上面的代码。 (请注意, j 在循环内永远不会等于2,因此您的条件仍然是错误的。)

There's no need for that j loop since each iteration does a completely different thing. Just write the j=0 case immediately followed by the j=1 case, and then get rid of the loop, like my code above. (And note that j will never equal 2 inside the loop, so your condition was wrong anyway.)

这篇关于使用getline和&gt;&gt;读取文件C ++时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆