There are actually two problems:
- how to recognize the entrance and ...
- how to imagine it in memory.
You talked about "2d Array": is it a requirement or just a hypothesis? 2x5 size required or just a sample?
You talked about the layout of the file. Is that necessary or not? Do you have to admit (and verify) the ultimate misleading as there are more numbers, or misalignment? What do you need to do if the line has 6 numbers first and 4 second?
A very simple solution can use a 2x5 array and fill it with a secure loop:
#include <iostream> #include <fstream> #include <iomanip> #include <stdexcept> const int ROWS=2; const int COLS=5; int main(int argc, char** argv) { int m[ROWS][COLS]; try { std::ifstream s(argv[1]); if(!s) throw std::runtime_error("cannot open file"); for(int r=0; r<ROWS; ++r) for(int c=0; c<COLS; ++c) if(!(s >>m[r][c]) throw std::runtime_error("insufficient or bad input"); } catch(const std::exception& e) { std::cout << "Reading error: " << e.what() << std::endl; return -1; } std::cout << "read matrix is \n"; for(int r=0; r<ROWS; ++r) { for(int c=0; c<COLS; ++c) std::cout << std::setw(8) << m[r][c]; std::cout << '\n'; } std::cout << std::endl; return 0; }
This will read 10 numbers separated by "spaces", regardless of how they are distributed and aligned. (2x5 is assumed to be an adversary.)
On the other hand, you may have to determine how wide the matrix is: a file can have any number of lines, each of which contains any number of elements.
In this case, you need a “flexible structure” and you need to identify the rows and elements in the rows.
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <iomanip> #include <stdexcept> #include <utility> int main(int argc, char** argv) { std::vector<std::vector<int> > m; try { std::ifstream fs(argv[1]); if(!fs) throw std::runtime_error("cannot open input file"); while(fs) { std::string line; std::getline(fs,line); std::vector<int> row; std::stringstream ss(line); int x; while(ss >> x) row.push_back(x); if(!row.empty()) m.emplace_back(std::move(row)); } } catch(const std::exception& e) { std::cout << "Reading error: " << e.what() << std::endl; return -1; } std::cout << "read lines: \n"; for(auto i=m.begin(); i!=m.end(); ++i) { for(auto j=i->begin(); j!=i->end(); ++j) std::cout << std::setw(8) << *j; std::cout << '\n'; } std::cout << std::endl; return 0; }
source share