0
0
C++programming~30 mins

File output using ofstream in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
File output using ofstream
πŸ“– Scenario: You are creating a simple program to save a list of favorite fruits to a text file. This is useful when you want to keep a record that can be opened later or shared.
🎯 Goal: Build a C++ program that writes a list of fruits to a file called fruits.txt using ofstream.
πŸ“‹ What You'll Learn
Create a vector of strings named fruits with the exact values: "Apple", "Banana", "Cherry"
Create an ofstream object named file to open fruits.txt
Use a for loop with variable fruit to write each fruit followed by a newline to the file
Close the file after writing
Print "Fruits saved to fruits.txt" to the console
πŸ’‘ Why This Matters
🌍 Real World
Saving data to files is common in many programs, like saving user preferences, logs, or reports.
πŸ’Ό Career
Understanding file output is essential for software developers working with data storage, logging, and configuration files.
Progress0 / 4 steps
1
Create the list of fruits
Create a std::vector<std::string> called fruits with these exact values: "Apple", "Banana", "Cherry".
C++
Need a hint?

Use curly braces {} to list the fruits inside the vector.

2
Open the file for writing
Add #include <fstream> at the top. Then create an std::ofstream object called file that opens the file named "fruits.txt".
C++
Need a hint?

Remember to include the <fstream> header to use ofstream.

3
Write fruits to the file
Use a for loop with variable fruit to write each fruit from fruits to the file followed by a newline using << operator.
C++
Need a hint?

Use a range-based for loop to go through each fruit and write it to the file.

4
Close the file and print confirmation
Close the file using file.close(). Then print "Fruits saved to fruits.txt" to the console using std::cout.
C++
Need a hint?

Call file.close() to save and close the file. Use std::cout to print the message.