知道文本文件中的列数,用空格或制表符分隔
know the number of columns from text file, separated by space or tab
我需要知道带有浮点的文本文件中的列数。
我这样做是为了知道行数:
inFile.open(pathV);
// checks if file opened
if(inFile.fail()) {
cout << "error loading .txt file for reading" << endl;
return;
}
// Count the number of lines
int NUMlines = 0;
while(inFile.peek() != EOF){
getline(inFile, dummyLine);
NUMlines++;
}
inFile.close();
cout << NUMlines-3 << endl; // The file has 3 lines at the beginning that I don't read
txt:的一行
189.53 58.867 74.254 72.931 80.354
值的数量可能因文件而异,但不在同一个文件上。
每个值在"."(点)后有一个可变的小数位数
这些值可以用空格或TAB分隔。
感谢
给定您已读过的一行,称为line
,该行有效:
std::string line("189.53 58.867 74.254 72.931 80.354");
std::istringstream iss(line);
int columns = 0;
do
{
std::string sub;
iss >> sub;
if (sub.length())
++columns;
}
while(iss);
我不喜欢这样读整行,然后重新编写,但它很有效。
还有各种其他的方法来分割字符串,例如boost的<boost/algorithm/string.hpp>
参见上一篇文章
您可以读取一行,然后将其拆分并计算元素数。
或者,您可以读取一行,然后将其作为数组进行迭代,并计算空格和t
字符的数量。
如果以下三个假设成立,您可以很容易地做到这一点:
- 定义了
dummyLine
,以便您可以在while
循环范围之外访问它 - 文件的最后一行具有相同的制表符/空格分隔格式(因为这就是
dummyLine
在while
循环后所包含的内容) - 每行数字之间只出现一个制表符/空格
如果所有这些都是真的,那么在while
循环之后,您只需要执行以下操作:
const int numCollums = std::count( dummyLine.begin(), dummyLine.end(), 't' ) + std::count( dummyLine.begin(), dummyLine.end(), ' ' ) + 1;
相关文章:
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 野牛/yacc 解析器在不被空格分隔时跳过 grammer - "unexpected $end"
- 从 stdio 获取一行空格分隔的整数,而不知道它们是多少 (C++)
- 如何从文件中读取用空格分隔的数字
- 反转由空格分隔的字符串元素将返回比原始字符串更大的字符串
- 获取由空格分隔的未知大小的单行输入,并将其存储到整数数组中
- 如果用户输入两个或多个由空格分隔的字符串C++如何防止缓冲区溢出?
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 非空格分隔的文本文件到 2D 矢量
- 如何在用空格分隔的行中获得无限的输入
- 如何从空格分隔的单个字符串中提取多个子字符串
- 如何获得一些用空格分隔的字符
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- C++ sscanf 空格分隔字符串
- 文本文件解析C++|用空格分隔
- 将空格分隔的输入读取到C++中的数组中