这是一个具有std::regex
(任意数量的名称)的解决方案:
auto extractNameAndAge(std::string const &s) -> std::tuple<std::string, int> {
using namespace std::string_literals;
static auto const r = std::regex{"(.*)\\s+(\\d+)\\s*$"s};
auto match = std::smatch{};
auto const matched = std::regex_search(s, match, r);
if (!matched)
throw std::invalid_argument{"Invalid input string \""s + s +
"\" in extractNameAndAge"s};
return std::make_tuple(match[1], std::stoi(match[2]));
}
测试:
auto main() -> int {
using namespace std::string_literals;
auto lines = std::vector<std::string>{"Jonathan Vincent Voight 76"s,
"Donald McNichol Sutherland 79"s,
"Scarlett Johansson 30"s};
auto name = ""s;
auto age = 0;
for (auto cosnt &line : lines) {
std::tie(name, age) = extractNameAndAge(line);
cout << name << " - " << age << endl;
}
}
输出:
Jonathan Vincent Voight - 76
Donald McNichol Sutherland - 79
Scarlett Johansson - 30