Loading...

C++ Reading a File

The throw page left one line on the screen in box.cpp: caught, after throw std::runtime_error("boom") and a matching catch. This page stays in the Errors and Files module on purpose. The workshop file on disk stays box.cpp so you keep one familiar build path. The new work opens a text file named note.txt, reads its first line with getline, and prints that line. The screen shows one line: pine.
Prepare note.txt by hand in the same folder as box.cpp. Put exactly one short line inside it: pine. On this page you write std::ifstream in("note.txt");, then std::string line;, then std::getline(in, line);, then std::cout << line << std::endl;. Reading ifstream is reading an input file stream. Reading getline is reading one line from that stream into line. The program does not create note.txt on this page.
Programs use file input when letters already live on disk after the program ends. You do not keep the throw and catch path as the lesson body on this page. Writing a file with C++ waits for the next page on purpose. Here the point is only opening note.txt, reading the first line, and printing pine. The build command stays familiar: one source file box.cpp, one output name box, one run that prints pine. Keep #include <iostream>, #include <fstream>, and #include <string> together at the top. You compile only box.cpp again for this workshop file on disk.
Think of note.txt as a sticky note beside the program. You write pine on that note in an editor first. Then box opens the note, copies the first line into line, and prints it. If the note is missing, the open fails and the print may be empty or wrong. Create the file before you run the checked workshop path.

Inside main, write std::ifstream in("note.txt");, then std::string line;, then std::getline(in, line);, then std::cout << line << std::endl;, then return 0;. Keep the three includes at the top of the file. Do not invent a write to disk on this page. Do not wait for keyboard input with cin.
Walk the run carefully from the first line of main. The program starts at main. ifstream opens note.txt. getline fills line with pine. Printing line shows pine on the screen. Then main returns and the program ends. There is one line on the screen. It is pine, not caught. The checked file always reads before it prints.
Say the steps out loud once while you read the file. Create note.txt with pine. Open it. Getline. Print line. Return. That short story is the whole workshop path. Nothing else belongs in the checked body. No throw. No ofstream write. No extra include beyond the three you already keep. When the screen shows pine, the story matched the source and the text file.

If note.txt is missing from the working folder, the open fails and the screen may not show pine. That failed experiment stays in the prose. The checked path always creates note.txt first with pine on the first line.
If you forget #include <fstream>, the build fails about std::ifstream. The checked file keeps that include next to iostream and string.
A common mistake is to wait for cin as if the letters came from the keyboard. Another common mistake is to invent writing the file with C++ on this page. A third mistake is to keep the old throw body and never open a file. A fourth mistake is to print a literal "pine" and never use getline. A fifth mistake is to put note.txt in a different folder than the one you run from.
This page stops before the next tool, where you write text out to a file. The next page names that tool once at the end. The read you have just written only shows opening note.txt and printing its first line. Keep the hand-made file beside box.cpp so the order stays clear for a first careful reading of the lesson.
Remember that reading does not create the file. You still prepare note.txt yourself. After a successful getline the screen is pine. After you undo a missing-file experiment the checked path returns to a real note with pine. Stability of the checked file and the note matters as much as learning ifstream itself.

Open box.cpp. Remove the throw and catch lines from the throw demo. Add #include <fstream> and #include <string> beside iostream. In main, open note.txt, call getline, and print line. Create note.txt beside the program with one line pine. The file name on disk for the program stays box.cpp. The checked program is below, and the new lines are the ifstream open, the getline call, and the print.

box.cpp reads pine from note.txt

cpp
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ifstream in("note.txt");
    std::string line;
    std::getline(in, line);
    std::cout << line << std::endl;
    return 0;
}

Rebuild with g++ -std=c++17 box.cpp -o box, then run ./box from the folder that also holds note.txt. If g++ is missing and clang++ is the compiler you installed, swap only the tool name: clang++ -std=c++17 box.cpp -o box. The screen shows one line: pine.
Check that line first on the screen. getline read pine from note.txt, so the print showed pine. The table gives each row its piece, so compare your run with it line by line before you move on to experiments. If the screen is empty, note.txt may be missing or in the wrong folder. If the screen shows caught, the old throw body is still there. If the build fails about ifstream, check #include <fstream>.

📊 file read and what the screen shows

Piece What the screen shows
First pine, because getline read the first line of note.txt
Last pine, because the program prints one line and stops
Rule ifstream opens a disk name; getline reads one line into a string
Screen pine

Try one change at a time. Temporarily change the first line of note.txt to oak, leave the program as it is, and rebuild so the screen shows oak. Restore pine in the text file. Next, temporarily rename the open string to "missing.txt" only long enough to see a failed read, then restore "note.txt" immediately. Each experiment changes one thing on purpose, so the screen shows either a different stored line or a missing-file problem. Undo each change before the next one starts, so the file always returns to the checked workshop version with note.txt holding pine and getline printing that line once again after every single careful try back on disk again.
This page ends the first files tool and stops before the next one. The next page is writing-files, which writes text out to a file. The read you have just written only shows opening note.txt in box.cpp. You leave with one line on the screen: pine. Count the lines before you leave. There is exactly one printed line on that final screen, and that single printed line on the screen is still just pine alone right there now after the final successful build run on disk today now after the getline print.

🧠 Test Your Knowledge

Ready to Start

Test Your Knowledge

Challenge yourself with this interactive quiz and see how well you understand the topic

❓
4
Questions
🎯
70%
To Pass
♾️
∞
Time
🔄
∞
Attempts

📝 Instructions

  • Read each question carefully
  • Select the best answer for each question
  • You can retake the quiz as many times as you want
  • Your progress will be shown at the top