The simplest line counter that I can think of would be something like this:
#include <string> #include <iostream> unsigned int count = 0; for (std::string line; std::getline(std::cin, line); ) { ++count; } std::cout << "We read " << count << " lines.\n";
Test:
echo -e "Hello\nWorld\n" | ./prog
If you want to discard empty lines, say if (!line.empty()) { ++count; } if (!line.empty()) { ++count; } instead.
source share