Person detail save/load
Write a program that checks for the existence of a file named person.txt. This file should contain a person's name, age, and address, each on a separate line. If the file exists, the program should read and display these details to the user. If the file does not exist, the program should prompt the user to enter these details and then save them to the file, with each piece of information on a separate line.
Program output when file found:
Details found in person.txt:
Name: John Doe
Age: 30
Address: 123 Main St, Springfield
Program output when file not found.
Enter name: Jane Smith
Enter age: 25
Enter address: 456 Elm St, Metropolis
Details saved to person.txt.
After this, person.txt will contain:
Jane Smith
25
456 Elm St, Metropolis
Answer
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("person.txt");
if (inFile) {
// File exists, read and display the details
std::string name, age, address;
std::getline(inFile, name);
std::getline(inFile, age);
std::getline(inFile, address);
std::cout << "Details found in person.txt:" << std::endl;
std::cout << "Name: " << name << std::endl;
std::cout << "Age: " << age << std::endl;
std::cout << "Address: " << address << std::endl;
} else {
// File does not exist, prompt for details
std::ofstream outFile("person.txt");
if (!outFile) {
std::cerr << "Error: Unable to create file." << std::endl;
return 1;
}
std::string name, age, address;
std::cout << "Enter name: ";
std::getline(std::cin, name);
std::cout << "Enter age: ";
std::getline(std::cin, age);
std::cout << "Enter address: ";
std::getline(std::cin, address);
outFile << name << std::endl;
outFile << age << std::endl;
outFile << address << std::endl;
std::cout << "Details saved to person.txt." << std::endl;
}
return 0;
}