如何从输入文件中查找未知数量的行和列
How to find unknown number of rows and cols from input file?
所以输入文件看起来类似于这样,它可以是任意的..:
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::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);
由于每行不包含空格,因此向量将包含所有行。 假设每行的宽度相同,则每个字符串的长度应该相同(您可以通过遍历向量并检查长度来轻松检查)。
我们可以通过这种方式更快地阅读它:
// 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
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 如何在C++中使用X509证书模在令牌中查找私钥
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在 for 循环中查找问题时遇到困难
- 如何在文件中查找字节序列
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 使用堆查找第K个最大元素的时间复杂性
- 一个函数,用于查找字符串1包含字符串2 c++的次数