0
0
C++programming~30 mins

Reading and writing files in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
Reading and writing files
πŸ“– Scenario: You are working on a simple program that saves and reads a list of favorite fruits to and from a file. This is useful when you want to keep your data even after the program stops running.
🎯 Goal: Build a C++ program that writes a list of fruits to a file and then reads the fruits back from the file to display them.
πŸ“‹ What You'll Learn
Create a vector of strings with exact fruit names
Create a string variable for the filename
Write the fruits to the file using ofstream
Read the fruits from the file using ifstream
Print each fruit read from the file
πŸ’‘ Why This Matters
🌍 Real World
Reading and writing files is a basic skill used in many programs to save user data, settings, or logs so the information is not lost when the program closes.
πŸ’Ό Career
Many software jobs require handling files for data storage, configuration, or communication between programs. Knowing how to read and write files is essential.
Progress0 / 4 steps
1
Create the list of fruits
Create a std::vector<std::string> called fruits with these exact entries: "Apple", "Banana", "Cherry", "Date", "Elderberry".
C++
Need a hint?

Use curly braces {} to list the fruit names inside the vector.

2
Set the filename
Create a std::string variable called filename and set it to "fruits.txt".
C++
Need a hint?

Use double quotes "" to set the filename string.

3
Write fruits to the file
Use std::ofstream to open the file with the name filename. Then use a for loop with variable fruit to write each fruit from fruits to the file, each on its own line. Close the file after writing.
C++
Need a hint?

Use std::ofstream to open the file and the insertion operator << to write each fruit followed by a newline.

4
Read fruits from the file and print
Use std::ifstream to open the file with the name filename. Use a std::string variable called line. Use a while loop with std::getline to read each line from the file into line. Inside the loop, print the line using std::cout. Close the file after reading.
C++
Need a hint?

Use std::getline inside a while loop to read each line and print it.