15.3. File inputΒΆ
std::ifstream, declared in <fstream>, reads from a file. Construct the
stream with a string containing the file name. Modern C++ accepts a
std::string directly; no conversion to a C string is required.
std::string file_name = "readings.txt";
std::ifstream input(file_name);
Check that the file opened, then check each read. A stream converts to a Boolean value that is false after a failed operation. Reading in a loop's condition avoids processing a value that was never successfully read.
12
7
19
1#include <fstream>
2#include <iostream>
3
4int main() {
5 std::ifstream input("c192_readings.txt");
6 if (!input) {
7 std::cerr << "Unable to open readings\n";
8 return 1;
9 }
10 int reading = 0;
11 while (input >> reading) {
12 std::cout << reading << '\n';
13 }
14 if (input.bad() || !input.eof()) {
15 std::cerr << "Unable to read an integer\n";
16 return 1;
17 }
18}
For whole lines, use while (std::getline(input, line)). A final line
without a newline is still a valid line and must be processed. Testing
eof() immediately after a successful getline can incorrectly discard
that line. Testing !eof() before reading can process stale data after a
failed read. Check the read itself instead.
std::string line;
while (std::getline(input, line)) {
std::cout << line << '\n';
}
Formatted extraction (>>) usually skips leading whitespace. getline
reads up to the next newline. If you mix them, remember that >> can leave
the newline in the stream, so the next getline may read an empty line.
One option is to read whole lines and parse each line with a separate string
stream, as we will do for the city records.
A file stream closes its file when it goes out of scope. This is an example of resource ownership: the object's lifetime controls the resource's lifetime.
We need to use the function c_str() to convert a string to a native C string because...
The standard-library type used to read from a file is .