我有一个这样划分的 .txt 文件:
(P1, 3): (E10, E20, E1, E3)
(P2, 2): (E10, E20, E2, E5)
(P3, 2): (E10, E20)
我只想将每一行的数字保存在一个数组中。例如:第一个是 [1,3,10,20,1,3]。我该怎么做?
最佳答案
使用 ifstream 逐行遍历文件.
将字符串读入 std::string,使用 regex search查找新读取的字符串中出现的数字。
要用于提取字符串中所有数字的正则表达式如下:
https://regex101.com/r/yWJp5p/3
用法示例:
#include <regex>
#include <iostream>
#include <string>
std::vector<std::string> fetchMatches(std::string str, const std::regex re) {
std::vector<std::string> matches;
std::smatch sm; // Use to get the matches as string
while (regex_search(str, sm, re)) {
matches.push_back(sm.str());
str = sm.suffix();
}
return matches;
}
int main() {
std::string example_input = "(P1, 3): (E10, E20, E1, E3)";
std::regex re{"\\d+"};
auto matches = fetchMatches(example_input, re);
for (const auto& match : matches) {
std::cout << match << std::endl;
}
return 0;
}
关于c++ - 从文件中的一行读取特定数据 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58685300/