0
0
C++programming~30 mins

File input using ifstream in C++ - Mini Project: Build & Apply

Choose your learning style9 modes available
File input using ifstream
πŸ“– Scenario: You have a text file named data.txt that contains a list of names, one per line. You want to read these names into your C++ program to process them.
🎯 Goal: Build a simple C++ program that reads all names from data.txt using ifstream and stores them in a vector.
πŸ“‹ What You'll Learn
Create an ifstream object to open data.txt
Check if the file opened successfully
Read each line (name) from the file into a std::string
Store all names in a std::vector<std::string>
Print all names after reading
πŸ’‘ Why This Matters
🌍 Real World
Reading data from files is common in many programs, such as loading user lists, configuration settings, or logs.
πŸ’Ό Career
Understanding file input with <code>ifstream</code> is essential for software developers working with data files, system utilities, or any application that processes external data.
Progress0 / 4 steps
1
Create an ifstream object to open the file
Write a line of code to create an std::ifstream object named inputFile that opens the file "data.txt".
C++
Need a hint?

Use std::ifstream followed by the variable name and the filename in parentheses.

2
Check if the file opened successfully
Add an if statement to check if inputFile is open. If not, print "Failed to open file." and return 1.
C++
Need a hint?

Use inputFile.is_open() to check if the file opened.

3
Read each line from the file into a vector
Declare a std::vector<std::string> named names. Use a std::string variable line and a while loop with std::getline(inputFile, line) to read each line and add it to names.
C++
Need a hint?

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

4
Print all names read from the file
Use a for loop with const std::string& name to iterate over names and print each name on its own line.
C++
Need a hint?

Use a range-based for loop to print each name.