【问题标题】:know the number of columns from text file, separated by space or tab知道文本文件的列数,用空格或制表符分隔
【发布时间】:2013-12-13 12:26:41
【问题描述】:

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

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

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

值的数量可能因文件而异,但不能在同一个文件中。

每个值在“.”之后都有可变的小数位数。 (点)

这些值可以用空格或制表符分隔。

谢谢

【问题讨论】:

    标签: c++ text-files multiple-columns


    【解决方案1】:

    鉴于您已阅读的名为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 的&lt;boost/algorithm/string.hpp&gt; 见上一篇here

    【讨论】:

      【解决方案2】:

      你可以读一行,然后split it 并计算元素的数量。

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

      【讨论】:

        【解决方案3】:

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

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

        如果所有这些都是真的,那么在while 循环之后,您只需要这样做:

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

        【讨论】:

        • 我得到一个错误:Error: Function count(dummyLine.begin(),dummyLine.end(),'\t') is not defined in current scope 你能指定count()吗?跨度>
        • 在文件顶部,此代码位于#include &lt;algorithm&gt;
        • 我用的是root,无法使用所有的C++功能,出现同样的错误...
        • 当您说您“使用 root”时,您的意思是您是 using namespace std; 还是其他意思?显然,您可以访问 std 功能,因为您使用的是 std::stringstd::fstream,因此只要包含算法,您也应该可以访问 std::count
        • 别忘了给女服务员小费,并接受正确答案。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多