[英]c++. How to add elements to a vector of pairs from file?
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.我正在尝试将每条奇数行读入 pair.first 并将每条偶数行读入 pair.second 并将其放入对的向量中。 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.不幸的是,它只读取前两行,向量 output 的 rest 只是零。
player
is a string and overall
is a integer, players
is my fstream file name. player
是一个字符串, overall
是 integer, players
是我的 fstream 文件名。
It's not a good idea to interleave std::getline
and operator>>
for reading an input stream.交错
std::getline
和operator>>
以读取输入 stream 不是一个好主意。 Instead, you'd better stick to using std::getline
twice here.相反,您最好在这里坚持使用
std::getline
两次。
Something like this would do:这样的事情会做:
std::getline
for this).std::getline
)。std::vector<std::pair<std::string, int>>
.std::vector<std::pair<std::string, int>>
。#include <charconv> // from_chars
#include <fmt/core.h>
#include <fmt/ranges.h>
#include <sstream> // istringstream
#include <system_error> // errc
#include <utility> // pair
#include <vector>
int main() {
std::istringstream iss{
"player1\n"
"1\n"
"player2\n"
"2ddd\n"
"player3\n"
"3 \n"
};
std::vector<std::pair<std::string, int>> players{};
for (std::string player{}, overall_str{};
getline(iss, player) and getline(iss, overall_str);) {
int overall{};
auto [ptr, ec] = std::from_chars(
overall_str.data(), overall_str.data() + overall_str.size(), overall);
if (ec == std::errc{}) {
players.push_back({player, overall});
} else {
fmt::print("Error parsing overall line: {}\n", overall_str);
continue;
}
}
fmt::print("{}\n", players);
}
// Outputs:
//
// [("player1", 1), ("player2", 2), ("player3", 3)]
You can strengthen the parsing of the overall line by:可以通过以下方式加强对整行的解析:
std::from_chars
used all of the input string to convert to a number.std::from_chars
使用所有输入字符串转换为数字。#include <boost/algorithm/string.hpp>
...
boost::algorithm::trim(overall_str);
...
if (ec == std::errc{} and ptr == overall_str.data() + overall_str.size()) {
// Outputs:
//
// Error parsing overall line: 2ddd
// [("player1", 1), ("player3", 3)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.