问题
So the input file will look similar to this, it can be arbitrary..:
000001000101000
010100101010000
101010000100000
I need to be able to find how many rows and columns are in the input file before I can start reading the file into a 2d array and I don't know if this is the right way to do it:
char c;
fin.get(c);
COLS = 0;
while ( c != '\n' && c != ' ')
{
fin.get(c);
++COLS;
}
cout << "There are " << COLS << " columns in this text file" << endl;
ROWS = 1;
string line;
while ( getline( fin, line ))
++ROWS;
cout << "There are " << ROWS << " rows in this text file" << endl;
If this is not the right way to do it or there is a more simple way please help me out.
I ALSO CAN'T USE THE STRING LIBRARY
回答1:
We can read it faster this way:
// get length of file:
fin.seekg (0, is.end);
int fileSize = fin.tellg();
fin.seekg (0, fin.beg);
std::string s;
if( getline( fin, s)) {
cols = s.size();
rows = fileSize/(cols+1); // cols+1 to count also '\n' at the end of each line
}
回答2:
If you were to use std::string and std::vector, this problem becomes trivial:
std::istream_iterator<std::string> start(fin); // fin is your std::ifstream instance
std::istream_iterator<std::string> end;
std::vector<std::string> lines(start, end);
Since each line contains no spaces, the vector will hold all of your lines. Assuming each line is the same width, each string should be of the same length (you can check that easy enough by iterating through the vector and checking the lengths).
来源:https://stackoverflow.com/questions/22002124/how-to-find-unknown-number-of-rows-and-cols-from-input-file