Skip to content

Instantly share code, notes, and snippets.

@naezith
Created September 19, 2018 23:27
Show Gist options
  • Save naezith/6c9fe7446f8988d29f3b48e882306cf3 to your computer and use it in GitHub Desktop.
Save naezith/6c9fe7446f8988d29f3b48e882306cf3 to your computer and use it in GitHub Desktop.
Read matrix with unknown sizes into vectors
#include <iostream>
#include <vector>
#include <fstream>
int main() {
std::ifstream file("data.txt");
if(!file) {
std::cerr << "Failed to open the file";
return 1;
}
std::vector<std::vector<int>> mat;
while(!file.eof()) {
// New row
mat.push_back(std::vector<int>());
// Read columns
int tmp;
while(file >> tmp) {
mat.back().push_back(tmp);
std::cout << mat.back().back();
if(file.peek() == '\n') break;
}
std::cout << std::endl;
}
file.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment