In: Computer Science
C++ Language
Problem 2 (Save and Get Info) : Write a program
that asks for the user's name, phone number, and address. The
program then saves all information in a data file (each information
in one line) named list.txt. Finally, the program
reads the information from the file and displays it on the
screen in the following format:
Name: User's Name
Phone Number: User's Phone Number
Address: User's Street Address
User's City, State, and Zip Code
Solution
Code
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
char data[100];
ofstream outfile;
outfile.open("list.txt");
cout << "Writing to the file" << endl;
cout << "Enter User name: ";
cin.getline(data, 100);
outfile << data << endl;
cout << "Enter your phone number: ";
cin >> data;
cin.ignore();
outfile << data << endl;
cout << "Enter your Address: ";
cin >> data;
cin.ignore();
outfile << data << endl;
cout << "Enter your City: ";
cin >> data;
cin.ignore();
outfile << data << endl;
cout << "Enter your State: ";
cin >> data;
cin.ignore();
outfile << data << endl;
cout << "Enter your zip code: ";
cin >> data;
cin.ignore();
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("list.txt");
cout << "Reading from the file" << endl;
infile >> data;
cout <<"Name: "<< data << endl;
infile >> data;
cout << "Phone Number: "<<data << endl;
infile >> data;
cout << "Address: "<<data << endl;
infile >> data;
cout <<"City: "<< data << endl;
infile >> data;
cout << "State: "<<data << endl;
infile >> data;
cout <<"Zip Code: "<< data << endl;
infile.close();
return 0;
}
Screenshot
Output
---
all the best