【问题标题】:How to count the number of lines of an input file? [duplicate]如何计算输入文件的行数? [复制]
【发布时间】:2015-10-29 18:24:46
【问题描述】:

我知道输入文件的每一行都包含五个数字,我希望我的 c++ 程序自动确定文件中有多少行而不询问用户。有没有办法在不使用 getline 或字符串类的情况下做到这一点?

【问题讨论】:

  • 这个问题的stackoverflow.com/questions/3482064/… 投票最多的答案提出了 2 种不使用 std::string 或 getline 的方法。一种解决方案是使用 getc() 读取 C 样式文件,一种是 C++ istream_iterator 解决方案。
  • 为什么不能使用getlinestd::string

标签: c++


【解决方案1】:

这就是我的做法......

#include <iostream> 
#include <fstream>

using namespace std;

int main()
{
    string fileName = "Data.txt";
    std::ifstream f(fileName, std::ifstream::ate | std::ifstream::binary);
    int fileSize = f.tellg() / 5 * sizeof(int);

    return 0;
}

代码假定一个名为 Data.txt 的文件,并且每行上的 5 个数字是 int 类型,并且没有用空格或分隔符分隔。请记住,在文本文件的情况下,每一行都会以换行符结束,因此这种不考虑它们的技术会产生误导性的结果。

【讨论】:

  • 这也假设每个数字只有一位。我怀疑是这样的。
  • @NathanOliver, 'sizeof(int)' 假设为一位数?
  • Opps 没有看到。 sizeof(int) 很可能会评估为 4 所以这假设会有 5、4 位数字
  • 是的,我让 Fred 来计算那部分。据我所知,他可以将它们存储为双精度或浮点数。
  • 用于在文件中存储int 的字节数不必是sizeof(int)
【解决方案2】:

当然,您所要做的只是读取文件,同时检查转义序列。请注意,\n 转义序列在写入时被转换为系统特定的换行符转义序列,反之亦然,而在 以文本模式阅读时。

一般来说,这段代码 sn-p 可能会对您有所帮助。

鉴于文件 somefile.txt

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

编译下面的代码并输入文件名somefile.txt

#include <iostream>
#include <fstream>

inline size_t newlineCount (std::istream& stream)
{
    size_t linesCount = 0;
    while (true)
    {
        int extracted = stream.get();
        if (stream.eof()) return linesCount;
        else if (extracted == '\n') ++linesCount;
    }
}

int main(int argc, char* argv[])
{
    std::string filename;
    std::cout << "File: ";
    std::cin >> filename;
    std::ifstream fileStream;
    fileStream.exceptions(fileStream.goodbit);
    fileStream.open(filename.c_str(), std::ifstream::in);
    if (!fileStream.good())
    {
        std::cerr << "Error opening file \"" << filename << "\". Aborting." << std::endl;
        exit(-1);
    }
    std::cout << "Lines in file: " << newlineCount(fileStream) << std::endl;
    fileStream.close();
}

给出输出

File: somefile.txt
Lines in file: 4

【讨论】:

  • @NeilKirk 感谢您的回复。我已经更新了检查后循环的答案。
  • get 到达文件末尾时返回。
  • @NeilKirk 将实现移至 inline size_t newlineCount (std::istream&amp; stream) 以提高可读性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-30
  • 2020-02-16
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-02-19
相关资源
最近更新 更多