面對每行長度不定、每行包含多組 `[C int int]` 格式數據的文本文件,核心挑戰在於:行數未知、每行配對數未知、整數範圍未知。本文提供結構化存儲方案與高效解析代碼。
採用 「行 → 配對列表」 的兩層動態結構:
// 單個配對
struct Pair {
int first; // 對應 [C 1 1] 中的 1
int second; // 對應 [C 1 1] 中的 1
};
// 一行數據 (動態數組)
using LineData = std::vector;
// 整個文件 (動態數組)
using FileData = std::vector;
優點:
✅ 無需預知行數與每行配對數
✅ 記憶體按需分配,無浪費
✅ 支援任意大小整數 (配合 `long long`)
避免一次性讀入整個文件 (可能超大),採用 `std::getline` 逐行處理,結合 `std::stringstream` 或手寫狀態機分割。
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <iostream>
#include <cctype>
struct Pair { int a, b; };
int main() {
std::ifstream fin("data.txt");
if (!fin) { std::cerr << "無法開啟文件\n"; return 1; }
std::vector> allLines;
std::string line;
while (std::getline(fin, line)) {
// 1. 過濾非數據行 (如 ###################begin##line...)
if (line.find('[') == std::string::npos) continue;
std::vector pairs;
std::stringstream ss(line);
char ch;
int n1, n2;
// 2. 利用流提取器自動跳過空白與分隔符
// 格式: [C 1 1] [C 1 7] ...
while (ss >> ch) { // 讀取 '['
if (ch != '[') continue;
char c; // 讀取 'C'
if (!(ss >> c)) break;
if (!(ss >> n1 >> n2)) break; // 讀取兩個 int
pairs.push_back({n1, n2});
ss >> ch; // 讀取 ']' (可選,下輪循環會處理下一個 '[')
}
if (!pairs.empty())
allLines.push_back(std::move(pairs));
}
// 3. 驗證輸出
for (size_t i = 0; i < allLines.size(); ++i) {
std::cout << "Line " << i+1 << ": ";
for (auto &p : allLines[i])
std::cout << "[" << p.a << "," << p.b << "] ";
std::cout << "\n";
}
return 0;
}
若文件達 GB 級,或需極致速度:
但對 99% 業務場景,上述 `getline + stringstream` 方案已足夠快且代碼極簡。