C++
Summary - File I/O
Combine ifstream, ofstream and getline to write a notes app.
Summary - File I/O
In this group you learned file input and output. std::ifstream reads, std::ofstream writes, std::fstream does both.
You check opening with is_open() and read line by line with std::getline. >> extracts whitespace-separated pieces, while std::getline reads up to a newline. By combining these two tools you can process structured text files. Now you will consolidate what you learned with two tasks: first counting lines, then summing numbers.
Exercise Count the lines in the file
The starting code writes three lines to data.txt. Open the file with std::ifstream, count the lines with a while (std::getline(in, line)) loop and print the count with std::cout.
Show example solution
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream out("data.txt");
out << "Line 1\nLine 2\nLine 3";
out.close();
std::ifstream in("data.txt");
std::string line;
int c = 0;
while (std::getline(in, line)) {
c++;
}
std::cout << c;
return 0;
}
Exercise Sum the numbers in the file
The starting code writes 10 20 30 to nums.txt. Open the file with std::ifstream, read numbers in a while (in >> n) loop, sum them and print the total with std::cout.
Show example solution
#include <iostream>
#include <fstream>
int main() {
std::ofstream out("nums.txt");
out << "10 20 30";
out.close();
std::ifstream in("nums.txt");
int n, t = 0;
while (in >> n) {
t += n;
}
std::cout << t;
return 0;
}
End of section
You completed file input and output. You can now read with std::ifstream, write with std::ofstream and do both with std::fstream.
You check safe opening with is_open() and read line by line with std::getline. These five concepts — reading, writing, combined streams, open checking and line reading — form the foundation of file handling in C++. The next groups cover string streams and move semantics.
Test yourself
-
Which function reads a whole line?
std::ifstream in("data.txt");
- in >> line
- std::getline(in, line)
- in.is_open()
- in.close()
Show answer
std::getline(in, line) — std::getline reads a whole line.
-
Complete the is_open check
if (in.____()) { std::cout << "Open"; }
Show answer
if (in.is_open()) { std::cout << "Open"; }
Next lesson: istringstream