In: Computer Science
Create a program that will loop and prompt to enter the highlighted data items in the structure below. This is every item except customerNumber , isDeleted and newLine;
const int NAME_SIZE = 20;
const int STREET_SIZE = 30;
const int CITY_SIZE = 20;
const int STATE_CODE_SIZE = 3;
struct Customers { long customerNumber; char name[NAME_SIZE]; char streetAddress_1[STREET_SIZE]; char streetAddress_2[STREET_SIZE]; char city[CITY_SIZE]; char state[STATE_CODE_SIZE]; int zipCode;
char isDeleted;
char newLine;
};
Always set the item isDeleted to 'N' and
newline to '\n'. The item newLine
is a convenient item that is there to assist in viewing the
contents of the file using "type filename" the cmd window.
Notepad will show the binary chars and will not line up the data as expected. You may see some odd characters after the expected data for the character arrays. That is normal for C/C++.
The item customerNumber should start at 0 and increase by 1 for every record written.
Once the data in the structure is loaded, write it to the file
"Customers.dat" and prompt to continue. If the reply is to not
continue, close the file and exit.
The file "Customers.dat" must be opened in Binary mode.
#include<iostream>
#include<fstream>
using namespace std;
const int NAME_SIZE = 20;
const int STREET_SIZE = 30;
const int CITY_SIZE = 20;
const int STATE_CODE_SIZE = 3;
// Structure
struct Customers
{
long customerNumber;
char name[NAME_SIZE];
char streetAddress_1[STREET_SIZE];
char streetAddress_2[STREET_SIZE];
char city[CITY_SIZE];
char state[STATE_CODE_SIZE];
int zipCode;
char isDeleted = 'N';
char newLine = '\n';
};
int main()
{
int n;
// Number of Data Entries (Loops)
cout<<"Enter the number of entries: ";
cin>>n;
struct Customers data[n];
for(int i=0; i<n; i++)
{
cout<<"enter name: ";
cin>>data[i].name;
cout<<"enter streetAddress_1: ";
cin>>data[i].streetAddress_1;
cout<<"enter streetAddress_2: ";
cin>>data[i].streetAddress_2;
cout<<"enter city: ";
cin>>data[i].city;
cout<<"enter state: ";
cin>>data[i].state;
}
// Write into the file
ofstream myfile;
myfile.open("Customers.dat", fstream::binary | fstream::out);
if (!myfile)
cout << "File Not Found." << endl;
else
{
for(int i=0; i<n; i++)
{
myfile << data[i].name << data[i].newLine << data[i].streetAddress_1 << data[i].newLine << data[i].streetAddress_2 <<
data[i].newLine << data[i].city << data[i].newLine << data[i].state << data[i].newLine << data[i].newLine;
}
}
myfile.close();
cout<< "Reading The (Customers.dat) file .............\n";
// Read from the file
ifstream instream("Customers.dat", fstream::binary | fstream::out);
string line;
// Read line by line
while (instream >> line)
{
cout << line;
if (instream.peek() == '\n') //detect "\n"
{
cout <<endl;
}
}
instream.close();
return 0;
}
Note :
Explanation:
Hope it helps. In case of any query please write it in the comment section.
Good Luck :)