Question

In: Computer Science

C++ 1. Modify this program to open the file "Customers.dat" so that all data is written...

C++

1. Modify this program to open the file "Customers.dat" so that all data is written to the end of the file AND to allow the file to be read.

2. Create a method called "getLargestCustomerNumber" and call it after the "Customers.dat" file has been opened. Read all the existing customerNumbers and determine the largest customerNumber - do not assume the last record in the file is the largest number. Use this number as the base when adding new customer data.

3. Display the customer number calculated for the customer number that is receiving input.

4. The program needs to create the Customers.dat file if it does not exist.

5. The program should be able to start multiple times and add data with increasing customerNumbers. There should be no duplicated customer numbers.

Must add comments to your program.

Imclude a pseudo Code for the getLargestCustomerNumber method.

PLEASE DO NOT use an already answered question here on CHEGG. unfortunately I've had that happen at many occasions

.......

P.S. : In the current program the file in not explicitly closed after my loop is done. Please fix that, and include the pseudo code for getLargestCustomerNumber method

I'll most certainly give an UPVOTE. I ALWAYS do with correct answers.

.......

.......

#include
#include
#include
using namespace std;

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;
};

int main()
{
// loop variable
char repeat;

do
{   
// New customers structure object
Customers c;
c.customerNumber = 0;

//opens file in binary mode
ofstream fp("Customers.dat", ios::out | ios::binary);
if (!fp)

{
cout << "File Cannot be opened" << endl;
return 0;
}
  
// Prompting and reading inputs
cout << "\nEnter Name: ";
cin.getline(c.name, NAME_SIZE);

cout << "\nEnter Address 1: ";
cin.getline(c.streetAddress_1, STREET_SIZE);

cout << "\nEnter Address 2: ";
cin.getline(c.streetAddress_2, STREET_SIZE);

cout << "\nEnter City: ";
cin.getline(c.city, CITY_SIZE);

cout << "\nEnter State: ";
cin >> c.state;

cout << "\nEnter Zip Code: ";
cin >> c.zipCode;

// Ignores rest of current line until '\n'
cin.ignore(numeric_limits::max(), '\n');

// Initializing isDeleted and newline
c.isDeleted = 'N';
c.newLine = '\n';

//increments customerNumber
c.customerNumber++;

//writes data to Customers.dat
// fp.write((char*)&c, strlen(Customers));
fp.write((char*)&c, sizeof(Customers));


cout << "\nEnter y/Y to continue or n/N to exit: ";
cin >> repeat;

cin.ignore(numeric_limits::max(), '\n');

// Quit if N/n is entered, otherwise loops
if (repeat == 'N' || repeat == 'n')
{
cout << " Exiting and closing file..........";
//closing the file
fp.close();
break;
}
  
} while (repeat == 'y' || repeat == 'Y');
return 0;
}

Solutions

Expert Solution

I have made chanegs to your code with required specs

Pseudocode for getLargestCustomerNumber

  • initialize cus_no to 0, this would mean that either there is no entry on the file or file does not exist
  • read all numbers from file until the file ends
  • for each new integer read, compare it with cus_no and update cus_no if it is less than the newly read entry.
  • return the cus_no, which now contains the largest customer number.

(code to copy)

#include<bits/stdc++.h>
using namespace std;

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;
};
int getLargestCustomerNumber(ifstream &infile){
        int cus_no = 0;
        int rd;
        while(infile>>rd){
                cus_no=max(rd,cus_no);
        }
        infile.close();
        return cus_no;
}
int main()
{
        // loop variable
        char repeat;

        do
        {   
                // New customers structure object
                Customers c;
                c.customerNumber = 0;

                
                //opens file to read
                ifstream infile("Customers.dat");
                if (!infile)
                {
                        cout << "File Cannot be opened. Creating new file" << endl;
                        infile.open("Customers.dat", ifstream::in | ifstream::out | ifstream::trunc);
                }
                
                int largestCustomerNumber = getLargestCustomerNumber(infile);
                cout<<"getLargestCustomerNumber() -> "<<largestCustomerNumber<<endl;

                // Prompting and reading inputs
                cout << "\nEnter Name: ";
                cin.getline(c.name, NAME_SIZE);

                cout << "\nEnter Address 1: ";
                cin.getline(c.streetAddress_1, STREET_SIZE);

                cout << "\nEnter Address 2: ";
                cin.getline(c.streetAddress_2, STREET_SIZE);

                cout << "\nEnter City: ";
                cin.getline(c.city, CITY_SIZE);

                cout << "\nEnter State: ";
                cin >> c.state;

                cout << "\nEnter Zip Code: ";
                cin >> c.zipCode;

                // Ignores rest of current line until '\n'
                cin.ignore(numeric_limits<streamsize>::max(), '\n');

                // Initializing isDeleted and newline
                c.isDeleted = 'N';
                c.newLine = '\n';

                //increments customerNumber
                c.customerNumber = largestCustomerNumber+1;

                // //opens file to write, use std::ios_base::app to append
                ofstream fp("Customers.dat", std::ios_base::app);
                //writes data to Customers.dat
                fp<<c.customerNumber<<endl;;


                cout << "\nEnter y/Y to continue or n/N to exit: ";
                cin >> repeat;

                cin.ignore(numeric_limits<streamsize>::max(), '\n');

                // Quit if N/n is entered, otherwise loops
                if (repeat == 'N' || repeat == 'n')
                {
                cout << " Exiting and closing file..........";
                //closing the file
                fp.close();
                break;
                }
                
        } while (repeat == 'y' || repeat == 'Y');
        return 0;
}

code screenshot

There was no file named Customers.dat before execution

Sample Input/Output Screenshot 1

Sample Input/Output Screenshot 2

Contents of Customer.dat after above executions

Let me know in the comments if you have any doubts.
Do leave a thumbs up if this was helpful.


Related Solutions

Program Requirements: Write a C++ program according to the following requirements: 1.   Open the data file...
Program Requirements: Write a C++ program according to the following requirements: 1.   Open the data file Electricity.txt and read each column into an array (8 arrays total). 2.   Also create 2 arrays for the following: Total Fossil Fuel Energy (sum of all fossil fuels) Total Renewable Energy (sum of all renewable sources) Electricity.txt: Net generation United States all sectors monthly https://www.eia.gov/electricity/data/browser/ Source: U.S. Energy Information Administration All values in thousands of megawatthours Year   all fuels   coal       natural gas   nuclear  ...
Modify this program so that it takes in input from a TEXT FILE and outputs the...
Modify this program so that it takes in input from a TEXT FILE and outputs the results in a seperate OUTPUT FILE. (C programming)! Program works just need to modify it to take in input from a text file and output the results in an output file. ________________________________________________________________________________________________ #include <stdio.h> #include <string.h> // Maximum string size #define MAX_SIZE 1000 int countOccurrences(char * str, char * toSearch); int main() { char str[MAX_SIZE]; char toSearch[MAX_SIZE]; char ch; int count,len,a[26]={0},p[MAX_SIZE]={0},temp; int i,j; //Take...
In c++, modify this program so that you allow the user to enter the min and...
In c++, modify this program so that you allow the user to enter the min and maximum values (In this case they cannot be defined as constants, why?). // This program demonstrates random numbers. #include <iostream> #include <cstdlib> // rand and srand #include <ctime> // For the time function using namespace std; int main() { // Get the system time. unsigned seed = time(0); // Seed the random number generator. srand(seed); // Display three random numbers. cout << rand() <<...
Modify the program written for Module 2 Activity 1 (Movie Data) to include two additional members...
Modify the program written for Module 2 Activity 1 (Movie Data) to include two additional members that hold the movie's production costs and first-year revenues. Modify the function that displays the movie data to display the title, director, release year, running time, and first year's profit or loss.
In c++  write a program. Give the necessary statements to open a file and to confirm that...
In c++  write a program. Give the necessary statements to open a file and to confirm that the file has been successfully opened for writing.
C Programming: POSIX: Producer / Consumer Modify the code below so that the Producer.c file calculates...
C Programming: POSIX: Producer / Consumer Modify the code below so that the Producer.c file calculates the Fibonacci sequence and writes the sequence to the shared-memory object. The Consumer.c file should then output the sequence. Producer.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <sys/shm.h> #include <sys/stat.h> #include <sys/mman.h> #include <zconf.h> int main() { /* The size (in bytes) of shared-memory object */ const int SIZE = 4096; /* The name of shared-memory object */ const char *Obj =...
•Modify p4.c so that the output file p4.output is created but also displayed to standard output...
•Modify p4.c so that the output file p4.output is created but also displayed to standard output ( the screen ). This should be done by another instance of exec(). •Implement the pipe() command to do the following: $> grep –o else p4.c | wc –l p4.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/wait.h> int main(int argc, char *argv[]) { int rc = fork(); if (rc < 0) {     // fork failed     fprintf(stderr, "fork...
Present a screenshot of the following Program to open up the created file in C++ language....
Present a screenshot of the following Program to open up the created file in C++ language. The list of random numbers will be below the instructions I have provided for you a file named Random.txt for use in this program. This file contains a long list of random numbers. You are to write a program that opens the file, reads all the numbers from the file and calculates the following: A. The number of numbers in the file B. The...
C ++ Data File Preparation 1. Using the original AL Weather Station Data file find all...
C ++ Data File Preparation 1. Using the original AL Weather Station Data file find all records that have a bad data flag (-9999) for either the PRCP, TMAX or TMIN fields. Produce a new data file (call it Filtered_AL_Weather_Station.txt ) that omits those records with bad data flags. This new file will be used in problem 2. NOTE: The temperatures are given in tenths of a degree Celsius. e.g 83 is 8.3 degrees C.    2. Using the filtered data...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year,...
Modify the Movie List 2D program -Modify the program so it contains four columns: name, year, price and rating (G,PG,R…) -Enhance the program so it provides a find by rating function that lists all of the movies that have a specified rating def list(movie_list): if len(movie_list) == 0: print("There are no movies in the list.\n") return else: i = 1 for row in movie_list: print(str(i) + ". " + row[0] + " (" + str(row[1]) + ")") i += 1...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT