rek*_*ove 3 c++ io loops vector matrix
我们在文本文件中有一个矩阵,数字之间有逗号,但每行末尾没有逗号。
1、2、3、4 7,8,2,1 3、4、5、6 7,2,1,3
我试图用这样的二维数组来做到这一点,但它并没有真正起作用,因为矩阵的大小也是未知的。
string array[4][4];
int id;
for (int i = 0; i < 4; i++) { // go through each line
for (int j = 0; j < 4; j++) {
getline(filein, numbers, ',');
array[i][j] = numbers;
cout << array[i][j] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我想使用 2D 矢量来做到这一点,但我不知道如何做到这一点。就像在创建一个向量之后
vector<vector<string>> matrix;
Run Code Online (Sandbox Code Playgroud)
我应该在循环内再创建一个向量吗?
使用向量的向量。以下是每一行的注释:
std::vector<std::vector<int>> v; // declare vector of vectors
std::ifstream ifs("myfile.txt"); // open the file
std::string tempstr; // declare a temporary string
int tempint; // declare a temporary integer
char delimiter; // declare a temporary delimiter
while (std::getline(ifs, tempstr)) { // read line by line from a file into a string
std::istringstream iss(tempstr); // initialize the stringstream with that string
std::vector<int> tempv; // declare a temporary vector for the row
while (iss >> tempint) { // extract the numbers from a stringstream
tempv.push_back(tempint); // push it onto our temporary vector
iss >> delimiter; // read the , delimiter
}
v.push_back(tempv); // push the vector onto vector of vectors
}
Run Code Online (Sandbox Code Playgroud)
完整的源代码是:
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <string>
int main() {
std::vector<std::vector<int>> v;
std::ifstream ifs("myfile.txt");
std::string tempstr;
int tempint;
char delimiter;
while (std::getline(ifs, tempstr)) {
std::istringstream iss(tempstr);
std::vector<int> tempv;
while (iss >> tempint) {
tempv.push_back(tempint);
iss >> delimiter;
}
v.push_back(tempv);
}
for (auto row : v) {
for (auto el : row) {
std::cout << el << ' ';
}
std::cout << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)