Write a C++ program that processes the data of a retail company with following r
ID: 3682555 • Letter: W
Question
Write a C++ program that processes the data of a retail company with following requirements:
1.Define a new data type (struct) of Customer, with following members: ID, first name, last name, number of items purchased, price of a single item, and total spending.
2.In the main function, declare an array of Customer.
3.The array should be created dynamically. In other words, you do not know how many customers when you write the program. The program can ask a user to enter a number, or better yet, let the code to count the number of records in the file.
4.The main function reads the data from a file of “customers.dat”.
Each row represents a customer’s record, with ID, first name, last name, number of item purchased and the price of a single item.
The data columns are separated by whitespaces.
5.Store the customer data in the array.
6.Design a function, computeTotals, to calculate the total spending of each customer:
total = numItems * price.
7.computeTotals takes two parameters, an array and the number of customers.
8.computeTotals must be coded with pointer notation (a 3-point deduction for non-pointer notations).
9.In the main function, print out all records, including the total spending, such as:
1001 Scott Adams 3 22.86 68.58
1002 Nicholas Allen 8 10.00 80.00
Explanation / Answer
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdlib.h>
using namespace std;
struct Customer{
long ID;
string first_name,last_name;
int numItems;
double price;
double total_spending;
};
void computeTotals(Customer* cust,int n);
int main(){
ifstream customer_file;
customer_file.open("customers.dat",ios::in);
int n;
string line;
for(n=0;getline(customer_file,line);){
if(line.length() > 0)
++n;
}
Customer* cust = new Customer[n];
customer_file.clear();
customer_file.seekg(0);
int i;
string str;
for(i=0;i<n;i++){
getline(customer_file,line);
istringstream iss(line);
iss >> str;
(*(cust + i)).ID = atol(str.c_str());
iss >> str;
(*(cust + i)).first_name = str;
iss >> str;
(*(cust + i)).last_name = str;
iss >> str;
(*(cust + i)).numItems = atoi(str.c_str());
iss >> str;
(*(cust + i)).price = atof(str.c_str());
}
computeTotals(cust,n);
for(i=0;i<n;i++){
cout << (*(cust+i)).ID << " "<< (*(cust + i)).first_name << " "<< (*(cust + i)).last_name <<
" "<< (*(cust + i)).numItems << " "<<(*(cust+i)).price << " "<<(*(cust + i)).total_spending << endl;
}
}
void computeTotals(Customer* cust, int n){
int i;
for(i=0;i<n;i++){
(*(cust+i)).total_spending = ((*(cust+i)).numItems) * ((*(cust+i)).price);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.