知道文本文件中的列数,用空格或制表符分隔

know the number of columns from text file, separated by space or tab

本文关键字:空格 分隔 制表符 文本 文件      更新时间:2023-10-16

我需要知道带有浮点的文本文件中的列数。

我这样做是为了知道行数:

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字符的数量。

如果以下三个假设成立,您可以很容易地做到这一点:

  1. 定义了dummyLine,以便您可以在while循环范围之外访问它
  2. 文件的最后一行具有相同的制表符/空格分隔格式(因为这就是dummyLinewhile循环后所包含的内容)
  3. 每行数字之间只出现一个制表符/空格

如果所有这些都是真的,那么在while循环之后,您只需要执行以下操作:

const int numCollums = std::count( dummyLine.begin(), dummyLine.end(), 't' ) + std::count( dummyLine.begin(), dummyLine.end(), ' ' ) + 1;