C++。如何将元素添加到文件对向量中?
我试图将每条奇数读成对。首先和每条偶数行,并将其放入成对的矢量中。我想在矢量中有一个球员和他的整体。 这是我的代码:
while(getline(players, player) && players >> overall)
{
pick_players.push_back(make_pair(player, overall));
}
不幸的是,它仅读取前两行,其余的向量输出只是零。 player
是字符串,总体
是整数,player
是我的fstream文件名。
I'm trying to read every odd line into pair.first and every even line to pair.second and put it into a vector of pairs. I'd like to have a player and his overall in one pair in a vector.
Here's my code :
while(getline(players, player) && players >> overall)
{
pick_players.push_back(make_pair(player, overall));
}
Unfortunately it reads only the first two lines and the rest of vector output are just zeros. player
is a string and overall
is a integer, players
is my fstream file name.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
交流
std :: getline
和操作员>>
用于阅读输入流是不是一个好主意。相反,您最好坚持使用std :: getline
在这里两次。这样的事情会做:
std :: getline
)。std :: vector< std :: pair< std :: string,int>>
。[demo]
您可以通过:
[demo]
It's not a good idea to interleave
std::getline
andoperator>>
for reading an input stream. Instead, you'd better stick to usingstd::getline
twice here.Something like this would do:
std::getline
for this).std::vector<std::pair<std::string, int>>
.[Demo]
You can strengthen the parsing of the overall line by:
std::from_chars
used all of the input string to convert to a number.[Demo]