Group
File Management in C++
Objective
1. Prompt the user to enter how many numbers they want to save.
2. Use a loop to collect the numbers from the user and store them in a file using `ofstream`.
3. After saving the numbers, reopen the file using `ifstream`.
4. Read the numbers from the file and display them on the console.
5. Make sure to close the file after each operation.
Implement a program that saves a list of numbers to a file and then reads them.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for standard I/O
#include <fstream> // Include for file stream operations
using namespace std;
int main() {
string fileName = "numbers.txt"; // File to store the numbers
int count; // Number of values to enter
// Ask user how many numbers they want to enter
cout << "How many numbers do you want to save? ";
cin >> count;
ofstream outFile(fileName); // Open file for writing
// Check if the file was opened successfully
if (!outFile) {
cout << "Error opening file for writing." << endl;
return 1; // Exit with error
}
// Loop to write numbers to the file
cout << "Enter " << count << " numbers:" << endl;
for (int i = 0; i < count; ++i) {
int num;
cin >> num;
outFile << num << " "; // Write each number followed by a space
}
outFile.close(); // Close the output file
ifstream inFile(fileName); // Open file for reading
// Check if the file was opened successfully
if (!inFile) {
cout << "Error opening file for reading." << endl;
return 1; // Exit with error
}
// Read and display the numbers from the file
cout << "Numbers read from file:" << endl;
int num;
while (inFile >> num) {
cout << num << " "; // Output each number
}
inFile.close(); // Close the input file
cout << endl;
return 0; // End of program
}
Output
How many numbers do you want to save? 4
Enter 4 numbers:
12
34
56
78
Numbers read from file:
12 34 56 78