如何将输入数据拆分至变量?多组行列数据处理方案咨询
处理单行多组行列数据的读取方案
针对你遇到的单行包含多组行列数据的场景(如8 2 3 7 1,需将8存入size,2、7存入column集合,3、1存入row集合),可以通过以下方式修改代码:
核心思路
- 将单个的
column和row变量替换为容器类型(比如vector),用来存储多组数据 - 先读取每行的第一个值作为
size,再循环读取后续成对的column和row,直到该行数据读取完毕
修改后的代码示例
如果数据是数值类型(更符合size、行列的实际用途):
#include <fstream> #include <sstream> #include <vector> #include <string> using namespace std; int main(int argc, char* argv[]) { ifstream input; input.open(argv[1]); string in_str; // 每行处理独立的数据集,容器放在循环内避免跨行数据混淆 while(getline(input, in_str)) { stringstream ss(in_str); int size; vector<int> columns, rows; // 读取第一个值作为size ss >> size; int col, row; // 循环读取成对的行列数据,直到该行流结束 while(ss >> col >> row) { columns.push_back(col); rows.push_back(row); } // 这里可添加当前行数据的处理逻辑,比如打印验证 // cout << "Size: " << size << endl; // cout << "Columns: "; // for(int c : columns) cout << c << " "; // cout << endl << "Rows: "; // for(int r : rows) cout << r << " "; // cout << endl; } input.close(); return 0; }
如果需要保留字符串类型(和你原代码逻辑一致),只需把int替换为string即可:
#include <fstream> #include <sstream> #include <vector> #include <string> using namespace std; int main(int argc, char* argv[]) { ifstream input; input.open(argv[1]); string in_str; while(getline(input, in_str)) { stringstream ss(in_str); string size; vector<string> columns, rows; ss >> size; string col, row; while(ss >> col >> row) { columns.push_back(col); rows.push_back(row); } // 处理当前行数据... } input.close(); return 0; }
关键说明
- 容器放在
getline循环内部,确保每行的size、columns、rows是独立数据集,不会和上一行数据混合 while(ss >> col >> row)会自动判断流是否还有有效数据,只要能成对读取到行列值就继续循环,适配任意多组行列的情况
内容的提问来源于stack exchange,提问作者tako
相关产品推荐
相关产品推荐

