Read a file and count its lines and words
Description: Write poem.txt with three lines, then read it and print the number of lines and words.
Hint:
std::getlinereads a line, and anistringstreamcounts the words of the line.
Solution
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::ofstream("poem.txt") << "Roses are red\nViolets are blue\nC++ is fun\n";
std::ifstream in("poem.txt");
std::string line;
int lines = 0, words = 0;
while (std::getline(in, line)) {
lines++;
std::istringstream ls(line);
std::string w;
while (ls >> w) words++;
}
std::cout << "Lines: " << lines << '\n' << "Words: " << words << '\n';
}
Output
Lines: 3
Words: 9
How it works
- The first stream is closed at the end of the line (RAII), so the file is complete before we read it.
Read C++ File Handling.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |