How to find unknown number of rows and cols from input file?

一世执手 提交于 2020-01-05 06:50:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!