c++ - 从文件中的一行读取特定数据 - C++

标签 c++

我有一个这样划分的 .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/

相关文章:

c++ - BST 错误 : new initializer expression list treated as compound expression

c++ - OpenCV cvSaveImage Jpeg 压缩因子

c++ - Qt:告诉程序从放置它的同一目录中读取其他文件

c++ - QT无法通过上下文菜单添加新图(QCustomPlot)

c++ - Reinterpret_cast和指针删除

c++ - 防止舍入错误

c++ - 在 ODEINT + THRUST 观察器中,接收到表达式必须是可修改左值的错误

c++ - 为什么我不能将 SetArgPointee() 与 googlemock 一起使用?

c++ - c++ 中的模板语法只是模板 <typename T> 吗?

c++ - WinAPI SetWindowLongPtr - 改变 windowProc