您需要选择正确的方法来解决该问题。
如果您想存储未知数量的列,则可以使用std::vector。它会随您的喜好动态增长。
如果你想存储未知数量的行和列,那么你将再次使用std::vector。但是此时一个vector的vector,So,一个二维的vector:std::vector<std::vector<std::string>>。
这将存储任意数量的行和任意数量的不同列。
接下来。要从一行中提取数据,或者更好地说,就是拆分行。
为此有一个特殊的专用迭代器。 std::sregex_token_iterator。你可以定义你正在寻找的模式。或者,您可以定义一个模式,即您不想要的分隔符。
而且由于正则表达式用途广泛,您可以构建满足您需求的复杂模式。
对于正 sarach 数字,您可以使用 R"(\d+)",对于负搜索分隔符,您可以使用 R"([\.;\\])"。
如果要搜索分隔符,可以在构造函数的最后一个参数中添加 -1。
为了得到分割线的结果,我们将使用std::vectors 范围构造函数。在这里您可以指定一个开始迭代器和一个结束迭代器和构造函数,连同std::sregex_token_iterator 将为您完成所有工作。
看下面的简单例子:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>
using Columns = std::vector<std::string>;
using Rows = std::vector<Columns>;
const std::string fileName{ "data.txt" };
const std::regex re{ R"(\d+)" };
int main() {
// Open file and check, if it could be opened
if (std::ifstream inputFileStream{ fileName }; inputFileStream) {
// Here we will store the result
Rows rows{};
// Read all complete text lines from text file
for (std::string line{}; std::getline(inputFileStream, line);) {
// Get the columns
Columns columns(std::sregex_token_iterator(line.begin(), line.end(), re), {});
// Add the columns to rows
rows.push_back(columns);
}
// Debug Ouput
for (const auto& row : rows) {
for (const auto& column : row) std::cout << column << ' ';
std::cout << '\n';
}
} // Error message, if file could not be opened
else std::cerr << "\nError:Could not open file '" << fileName << "'\n\n";
return 0;
}
使用 C++17 编译