如何从输入文件中查找未知数量的行和列

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

本文关键字:未知数 查找 输入 文件      更新时间:2023-10-16

所以输入文件看起来类似于这样,它可以是任意的..:

000001000101000
010100101010000
101010000100000

我需要能够找到输入文件中有多少行和列,然后才能开始将文件读取到 2d 数组中,我不知道这是否是正确的方法:

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;

如果这不是正确的方法,或者有更简单的方法,请帮助我。

我也不能使用字符串库

如果你使用 std::stringstd::vector ,这个问题变得微不足道:

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);

由于每行不包含空格,因此向量将包含所有行。 假设每行的宽度相同,则每个字符串的长度应该相同(您可以通过遍历向量并检查长度来轻松检查)。

我们可以通过这种方式更快地阅读它:

// 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
}