Group
File Management in C++
Objective
1. Prompt the user to enter their name and age.
2. Open a file in write mode using `ofstream`.
3. Write the collected information into the file.
4. Close the file once the writing operation is complete.
5. Inform the user that their information has been saved.
Create a program that records information into a file (such as name and age).
Example C++ Exercise
Show C++ Code
#include <iostream> // Include for standard input and output
#include <fstream> // Include for file output stream
#include <string> // Include for using the string class
using namespace std;
int main() {
string name; // Variable to store the user's name
int age; // Variable to store the user's age
// Prompt the user to enter their name
cout << "Enter your name: ";
getline(cin, name); // Read the full name including spaces
// Prompt the user to enter their age
cout << "Enter your age: ";
cin >> age; // Read the user's age
ofstream outFile("userdata.txt"); // Create and open a file named 'userdata.txt'
// Check if the file was opened successfully
if (outFile.is_open()) {
// Write the name and age into the file
outFile << "Name: " << name << endl;
outFile << "Age: " << age << endl;
outFile.close(); // Close the file after writing
cout << "Information saved successfully to 'userdata.txt'." << endl;
} else {
// Display an error if the file could not be opened
cout << "Error: Could not open file for writing." << endl;
}
return 0; // End of program
}
Output
//Output Example:
Enter your name: Alice Johnson
Enter your age: 28
Information saved successfully to 'userdata.txt'.
//Content of userdata.txt:
Name: Alice Johnson
Age: 28