如何从输入文件中找到未知的行数和列数? [英] How to find unknown number of rows and cols from input file?
本文介绍了如何从输入文件中找到未知的行数和列数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ $ $ $ $ $ c $ 000001000101000
010100101010000
101010000100000
我需要能够查找输入中有多少行和列文件之前,我可以开始阅读文件到一个二维数组,我不知道这是否是正确的方式来做到这一点:
char c;
fin.get(c);
COLS = 0;
while(c!='\\\
'&&c!='')
{
fin.get(c);
++ COLS;
}
cout<< 有<< COLS<< 此文本文件中的列<< ENDL;
ROWS = 1;
字符串行;
while(getline(fin,line))
++ ROWS;
cout<< 有<< ROWS< 此文本文件中的行<< ENDL;
如果这不是正确的方法,或者有更简单的方法,请帮助我。
我也不能使用字符串库
解决方案
//获取文件长度:
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在每行的末尾也计算'\\\
'
}
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
解决方案
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
}
这篇关于如何从输入文件中找到未知的行数和列数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文