Im writing a program that stores zip codes with corresponding cities in a sequential access file. This I have no problem with. The program also has to display the city corresponding with the zip code entered by the user, and vice versa. I am confused on what to do for this part of the program.
//Ch13Ex1.cpp – saves cities and ZIP codes to a sequential access file
//and also displays the city corresponding to a ZIP code
#include <iostream>
#include <string>
#include <fstream>
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::ifstream;
using std::ofstream;
using std::ios;
//function prototypes
int displayMenu();
void addRecords();
void displayCity();
void displayZip();
int main()
{
//declare variable
int menuChoice = 0;
//display menu and get choice
menuChoice = displayMenu();
//call appropriate function
//or display error message
while (menuChoice != 4)
{
if (menuChoice == 1)
addZipcity();
elseif (menuChoice == 2)
displayCity();
elseif (menuChoice == 3)
displayZip();
else
cout << "Invalid menu choice" << endl;
//end ifs
//display menu and get choice
menuChoice = displayMenu();
} //end while
return 0;
} //end of main function
//*****function definitions*****
int displayMenu()
{
//declare variable
int choice = 0;
//display menu
cout << "Options" << endl;
cout << "1 Add Zip/City" << endl;
cout << "2 Display City" << endl;
cout << "3 Display Zip Code" << endl;
cout << "4 Exit Program" << endl;
//get user's choice, then return the choice
cout << "Enter menu option: ";
cin >> choice;
cin.ignore(1);
return choice;
} //end of displayMenu function
void addRecords()
{
string zip = "";
string city = "";
ofstream outFile;
outFile.open("zipcity.txt", ios::app);
if (outFile.is_open())
{ //get the name
cout << "Enter zip code (X to stop): ";
getline(cin, zip);
while (zip != "X" && zip != "x")
{
//get the city
cout << "Enter city: ";
getline(cin, city);
cin.ignore();
//write the record
outFile << zip << '#' << city << endl;
//get another name
cout << "Enter zip (X to stop): ";
getline(cin, zip);
} //end while
//close the file
outFile.close();
} //end if
else
cout << "File could not be opened." << endl;
//end if
} //end of addZipcity function
void displayCity()
{
//declare variables
string input = "";
string zip = "";
string city = "";
bool found = false;
//create file object and open the file
ifstream inFile;
inFile.open("zipcity.txt", ios::in);
//determine whether the file was opened
if (inFile.is_open())
{
//read a record
cout << "Enter zip code: ";
cin >> zip;
while (!inFile.eof() && !found)
{
cout << "City: " << city << endl;
//read another line from the file
getline(inFile, input);
} //end while
//close the file
inFile.close();
}
else
cout << "File could not be opened." << endl;
//end if
}
void displayZip()
{
}
for void displayZip() I know I'd essentially have to reverse whatever I did in void displayCity().