因此输入文件看起来与此类似,它可以是任意的..:
000001000101000
010100101010000
101010000100000
在我开始将文件读入二维数组之前,我需要能够找到输入文件中有多少行和列,我不知道这是否是正确的方法:
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::string
和 std::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);
由于每行不包含空格, vector 将包含所有行。假设每条线的宽度相同,则每个字符串的长度也应相同(您可以通过遍历 vector 并检查长度来轻松检查这一点)。
关于c++ - 如何从输入文件中查找未知数量的行和列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22002124/