繁体   English   中英

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

[英]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/algorithm/string.hpp>见以前的帖子在这里

您可以阅读一行,然后将其拆分并计算元素数量。

或者,您可以读取一行,然后将其作为数组进行遍历,并计算空格\\t字符的数量。

如果这三个假设是正确的,则可以很容易地做到这一点:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM