0

Currently using:

{
std::ifstream inFile("test.txt");
int x = std::count(std::istreambuf_iterator<char>(inFile), std::istreambuf_iterator<char>(), '\n');

cout<<x<<endl;
}

Though, I'm looking to disclude lines starting with comments (I.E. '//'), thoughts? Or, would I need to write this with something else completely?

EDIT::

I wound up going a different route entirely so that I would be capable of counting all lines of all files in the current working directory.

  • Probably `std::accumulate` with line-based iterators and counting within the accumulator function. – chris Nov 18 '14 at 18:17

3 Answers3

2

First, you need to read the file line by line. There's a nice way of doing it through a std::string proxy. Second, you need to use std::count_if so that you can pass a predicate which will determine whether the line starts with the comment sequence or not.

#include <string>
#include <vector>
#include <iostream>
#include <fstream>

#include <boost/algorithm/string/predicate.hpp>

class line
{
  std::string data;

public:
  friend std::istream& operator>>(std::istream& is, line& l)
  {
    std::getline(is, l.data);
    return is;
  }

  operator std::string() const
  {
    return data;
  }
};

int main()
{
  std::ifstream file("./test.txt");

  auto count = std::count_if(std::istream_iterator<line>(file),
                             std::istream_iterator<line>(), [](const line& l) {
    return !boost::algorithm::starts_with(static_cast<std::string>(l), "//");
  });

  std::cout << count << std::endl;

  return 0;
}
Community
  • 1
  • 1
Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52
1

You can set up a filtering streambuf that discards lines beginning with //. The stream should wrap around the file buffer of inFile. James Kanze does something similar in his article:

David G
  • 94,763
  • 41
  • 167
  • 253
0

I would think iterating over the lines and use a predicate function would be the way

aivision2020
  • 619
  • 6
  • 14