【问题标题】:C++ fileIO line countC++ fileIO 行数
【发布时间】:2016-11-26 21:32:40
【问题描述】:
ifstream inFile;
inFile.open(filename); //open the input file

stringstream strStream;
strStream << inFile.rdbuf(); //read the file

string str = strStream.str(); //str holds the content of the file

我正在使用此代码从文件中读取。我需要获取该文件的行数。有没有办法在不第二次读取文件的情况下做到这一点?

【问题讨论】:

标签: c++ file input newline counter


【解决方案1】:

你已经有了一个字符串中的内容,所以只需检查那个字符串:

size_t count = 0, i = 0, length = str.length();
for(i=0;i<length;i++)
    if(str[i]=='\n') count++;

【讨论】:

    【解决方案2】:

    我很想这样做:

    auto no_of_lines = std::count(str.begin(), str.end(), '\n');
    

    【讨论】:

      【解决方案3】:

      algorithm 库中的std::count 可以帮助您。

      #include <algorithm>
      #include <iterator>
      
      //...
      
      long long lineCount { std::count(
              std::istreambuf_iterator<char>(inFile),
              std::istreambuf_iterator<char>(),
              '\n') };
      
      std::cout << "Lines: " << lineCount << std::endl;
      

      【讨论】:

      • 不完全正确。 std::count 返回Iterator::difference_type,在本例中为std::char_traits&lt;char&gt;::off_type,该类型由实现定义。我的观点是,如果你想确保使用正确的返回类型,你应该使用 auto 而不是 long long
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 2016-01-28
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多