1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
|
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "TestAddress.txt";
int main() {
menu();
return 0;
} //end main
void menu(void) {
//allow user to choose to append records, display records or exit the program
char choice = ' ';
do
{
// would you like to append records, show records, or exit?
cin >> choice;
choice = toupper(choice);
switch (choice)
{
case 'A':
writeData();
break;
case 'D':
readData();
break;
case 'E':
break;
}
} while (choice != 'E');
}
//end menu
void writeData(void)
{
//Write the Address Info to a file
string name, street, city, state, zip;
ofstream outMyStream(FileName, ios::app);
//loop while user still has data to write to file
if (outMyStream.is_open())
{
cout << "Enter your name: ";
getline(cin, name);
cout << "Enter your street: ";
getline(cin, street);
cout << "Enter your city: ";
getline(cin, city);
cout << "Enter your state: ";
getline(cin, state);
cout << "Enter your zip code: ";
getline(cin, zip);
//eg outStream<<name<<”#”; //where # is the delimiter
outMyStream << name << "#";
outMyStream << street << "#";
outMyStream << city << "#";
outMyStream << state << "#";
outMyStream << zip << "#";
}
outMyStream.close();
}//end write data
void readData(void) {
//read data from a file
//use the split function to break a
//deliminated line of text into fields
ifstream inMyStream(FileName);
if (inMyStream.is_open()) {
//set character to use as a line between record displays
string recBreaks = "";
recBreaks.assign(20, '-');
int fieldCount = 0; //keep track of the number of fields read
int recordCount = 1; //keep track of the number of records read
//read the first field
fieldCount = 1;
string fieldBuffer;
getline(inMyStream, fieldBuffer, '#');
while (!inMyStream.eof()) {
//display the field
switch (fieldCount) {
case 1:
cout << recBreaks << endl;
cout << "record # " << recordCount << endl;
cout << "Name...." << fieldBuffer << endl; break;
case 2:
cout << "Street.." << fieldBuffer << endl; break;
case 3:
cout << "City...." << fieldBuffer << endl; break;
case 4:
cout << "State..." << fieldBuffer << endl; break;
case 5:
cout << "Zip....." << fieldBuffer << endl;
fieldCount = 0;
recordCount++; break;
}
//read the next field
getline(inMyStream, fieldBuffer, '#');
fieldCount++;
}
cout << recBreaks << endl;
inMyStream.close();
}//end read data
|