我是编程新手,我想从字符串中存储2个整数并将它们存储在各自的变量中。
答案 0 :(得分:1)
您可能希望将regex用于此目的。
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main()
{
std::string s = "string 5 another string 6";
std::regex digit_regex("(\\d+)");
auto digits_begin = std::sregex_iterator(s.begin(), s.end(), digit_regex);
auto digits_end = std::sregex_iterator();
std::cout << "Found "
<< std::distance(digits_begin, digits_end)
<< " digits \n";
for (std::sregex_iterator i = digits_begin; i != digits_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << "Found digit: " << match_str << std::endl;
}
}
示例输出:
Found 2 digits
Found digit: 5
Found digit: 6