setPercent function is printing garbage data [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Just started working with OOP and it hasnt been very fun. im writing a program where the user chooses 3options from a menu (1. print all 2. change score 3. quit) Im stuck on the print all function. I want to print out 3 things the name of each student their percent and their scores(the scores and names are read in from a file). Problem is percent keeps printing out garbage data. So i did some debugging and i found out that when i read in the scores of each student its reading in extra values of garbage data which is ruining the calculation. I've tried to fix it but havent had any luck. All help and tips are appreciated below is the code and i will also post the IMG of my debugging and the garbage data i found being stored in scores[i].
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
class Student
{
private:
string name;
int *scores;
int numstu;
int numscores;
int maxscore;
double percent;
public:
//Mutator
void setName(string inName) {name = inName;}
void setNumstu(int iNum) {numstu = iNum;}
void setNumscores(int sNum) {numscores = sNum;}
void setMaxscore(int mNum) {maxscore = mNum;}
void setScores(int *list);
void setPercent ();
//Accessor
string getName () const {return name;}
int getNumScores () const {return numscores;}
int getNumStu () const {return numstu;}
int getMaxScore () const {return maxscore;}
double getPercent () const {return percent;}
int *getScoreslist () const {return scores;}
//constructor
//Student();
};
void Student::setScores(int *list)
{
scores = new int[numscores];
for (int i = 0; i < numscores; i++)
{
scores[i] = list[i];
}
};
void Student::setPercent()
{
double sum = 0;
//debugging shows scores is being filled with garbage data
for (int i = 0; i < numscores; i++)
{
cout << scores[i] << endl;
}
for(int i = 0; i < numscores; i++)
{
sum = sum + scores[i];
}
//cout << sum;
percent = (sum/maxscore) * 100.0;
sum = 0;
//cout << percent;
};
Student *fillArr(int &numstu, int &numscores, int &maxscore);
void printAll(Student *stuArr, int numstu, int numscores);
int main()
{
int numstu;
int numscores;
int maxscore;
int choice;
Student *stuArr;
stuArr = fillArr(numstu, numscores, maxscore);
if(stuArr == 0)
{
cout << "Error." << endl;
return 0;
}
cout << "Menu:" << endl;
cout << "1. Print All" << endl;
cout << "2. Change Score" << endl;
cout << "3. Quit" << endl;
cin >> choice;
do
{
if(choice == 1)
{
printAll(stuArr, numstu, numscores);
}
else if (choice == 2)
{
cout << "Change Score" << endl;
}
else if (choice == 3)
{
cout << "Good Bye" << endl;
exit(100);
}
else
{
cout << "That is not a valid option." << endl;
return 0;
}
} while (choice !=1 && choice !=2 && choice != 3);
return 0;
};
Student *fillArr(int &numstu, int &numscores, int &maxscore)
{
//Opening file and checking if it exists
ifstream infile;
infile.open("grades.txt");
if(!infile)
{
cout << "Error Opening file\n";
return 0;
}
string temp;
//Reding in number of students, number of scores, and maximum score
infile >> numstu >> numscores >> maxscore;
//Dynamically Allocating new memory for each student
Student *newStu = new Student[numstu];
infile.ignore();
for (int i = 0; i < numstu; i++)
{
getline(infile, temp);
newStu[i].setName(temp);
newStu[i].setMaxscore(maxscore);
newStu[i].setNumscores(numstu);
int *list = new int[numscores];
for (int z = 0; z < numscores; z++)
{
infile >> list[z];
};
newStu[i].setScores(list);
infile.ignore();
};
return newStu;
infile.close();
};
void printAll(Student *stuArr, int numstu, int numscores)
{
cout << "Name\t" << "\tGrade\t" << "\tScores\t" << endl;
for (int i = 0; i < numstu; i++)
{
//calling setpercent mutator
stuArr[i].setPercent();
cout << setprecision(1) << fixed << left;
//printing out each name and percent of each student
cout << setw(20) << stuArr[i].getName() << setw(19) << stuArr[i].getPercent() << setw(20);
printing out the scores of each student works correctly here for some odd reason
const int *ptr = stuArr[i].getScoreslist();
for (int z = 0; z < numscores; z++)
{
cout << left;
cout << setw(4) << ptr[z];
}
cout << endl;
}
};

Found the bug in this line: newStu[i].setNumscores(numstu); it should be newStu[i].setNumscores(numscores); instead

Related

How can I allocate the right amount of memory to this? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 months ago.
Improve this question
This has somehow become susceptible to buffer overflow. Not sure why or how to fix it?
ps. I am new to programming and any tips to improve the overall quality of the code would be greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int numberSeries[] = { 1 };
int seriesSize;
int checkOrder = 1;
int counter = 0;
int i = 0;
string arr[] = { "test" };
string value;
string import;
string fileLocation;
void CreateArrayFromFile(string fileLocation);
void InputNumbers();
void PrintArray();
int Iteration(int size, int array[]);
void SwapNumbers(int arrayLocation, int array[]);
int main()
{
cout << "What you like to numbers 'import' from file or 'manually' enter the numbers? \n";
cin >> import;
if (import == "import") {
cout << "Input file location using full path: ";
cin >> fileLocation;
CreateArrayFromFile(fileLocation);
}
else if (import == "manually") {
InputNumbers();
PrintArray();
while (counter < seriesSize) {
Iteration(seriesSize, numberSeries);
}
}
else {
cout << "INVALID SELECTION";
}
}
void InputNumbers() {
cout << "What is the required size of the array? \n";
cin >> seriesSize;
cout << "Enter " << seriesSize << " numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cin >> numberSeries[i];
}
cout << "\n";
}
void PrintArray() {
cout << "Here are your current numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cout << numberSeries[i] << " ";
}
cout << "\n";
}
int Iteration(int size, int array[]) {
for (int i = 0; i < (seriesSize - 1); i++) {
if (numberSeries[i] > numberSeries[i + 1]) {
SwapNumbers(i, numberSeries);
counter = 0;
}
else if (numberSeries[i] <= numberSeries[i + 1]) {
counter++;
}
}
if (counter >= seriesSize) {
cout << "YOUR NUMBERS HAVE BEEN SORTED\n\n";
}
else {
PrintArray();
cout << "Iteration complete!\n\n";
}
return 0;
}
void SwapNumbers(int arrayLocation, int array[]) {
int tempSwapOne, tempSwapTwo;
//store each number
tempSwapOne = array[arrayLocation];
tempSwapTwo = array[arrayLocation + 1];
//assign number to new location
array[arrayLocation] = tempSwapTwo;
array[arrayLocation + 1] = tempSwapOne;
}
void CreateArrayFromFile(string fileLocation) {
ifstream file;
file.open(fileLocation, ios::in);
int* ptr = (int*)malloc(sizeof(file));
cout << *ptr;
string line;
int i = 0;
if (file.is_open()) {
while (!file.eof())
{
getline(file, line);
arr[i] = line;
i++;
}
seriesSize = i;
}
else {
cout << "File could not be opened. Check path is correct...\n\n";
return;
}
for (i = 0; i < seriesSize; i++) {
int tempNumber = stoi(arr[i]);
numberSeries[i] = tempNumber;
cout << numberSeries[i] << " ";
}
cout << "\nTotal numbers: " << seriesSize;
}
I tried to assign the correct amount of memory but I have no idea how to figure out the correct amount.
Use std::vector instead. It handles the memory management and will automatically resize.

Quick sort of dynamic massive of objects doesn't work correctly [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In my task I have to make class city, which have data members
width(GeografskaShirina)
lenght(GeografskaDaljina)
ime(name)
NadmorskaVisochina(height)
I have constructor by defalut,which input data, copy constructor and predefinition of operator = .
I should sort my dynamic array bulgaria by GeografskaDaljina(length), using quick sort, which I realized in method of class quicksort. I have also a Output() method(to print sorted names of cities), method getDaljina(),which returns GeografskaDaljina(length).
The problem is that when I call quicksort in main(), sorting doesn't work correctly and doesn't print wishing results.
#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class city {
private:
string ime;
double GeografskaShirina;
double GeografskaDaljina;
double NadmorskaVisochina;
public:
city();
double getDaljina();
string getN();
void Output();
city(const city& p);
city& operator = (const city& p);
void quicksort(city bulgaria[], int left, int right);
};
city::city(const city& p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
city& city::operator = (const city& p)
{
if (this != &p)
{
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
}
return *this;
}
city::city()
{
cout << "Vavedete ime grad: ";
cin >> ime;
cout << "Vavedete geografskata shirina na grada: ";
cin >> GeografskaShirina;
cout << "geografskata daljina na grada: ";
cin >> GeografskaDaljina;
cout << "Vavedete nadmorska visochina na grada: ";
cin >> NadmorskaVisochina;
cout << "---------------------------------" << endl;
}
void city:: quicksort(city bulgaria[], int left, int right)
{
int min;
min = (left + right) / 2;
cout << left << endl;
cout << right << endl;
int i = left;
int j = right;
int pivot = bulgaria[min].getDaljina();
while (left < j || i < right)
{
while (bulgaria[i].getDaljina() < pivot)
i++;
while (bulgaria[i].getDaljina()>pivot)
j--;
if (i <= j)
{
city temp = bulgaria[i];
bulgaria[i] = bulgaria[j];
bulgaria[j] = temp;
i++;
j--;
}
else
{
if (left < j)
{
quicksort(bulgaria, left, j);
}
if (i < right)
{
quicksort(bulgaria, i, right);
}
return;
}
}
return;
}
double city::getDaljina() {
return GeografskaDaljina;
}
string city::getN() {
return ime;
}
void city::Output()
{
cout << "Imeto e " << ime << endl;
cout << "Geografskata shirina e " << GeografskaShirina << endl;
cout << "Geografskata duljina e " << GeografskaDaljina << endl;
cout << "Nadmorskata visochina e " << NadmorskaVisochina << endl;
}
int main()
{
int n;
int i=0;
cout << "Broi gradove : ";
cin >> n;
cout << endl;
city *bulgaria = new city[n];
bulgaria[i].quicksort(bulgaria, 0,n-1);
for (int i = 0; i < n; i++)
{
bulgaria[i].Output();}
return 0;}
You use the wrong index in the second while loop in city::quicksort. You schold use j to compare the right value with the pivot value:
while (bulgaria[j].getDaljina()>pivot)
j--;

Memory Allocation Issues Passing/Returning a Struct *Array

Please help me with my homework. I've got this program working just fine in debug mode, but as soon I use release mode it crashes with an abort().
I know it probably has something to do with memory allocation, but I don't understand pointers well enough.
Requirement is that I have to use an *array to dynamically allocate memory.
"Your program should work for any number of students. When the program
starts, it should ask the user for the number of students to be
processed. Then it should dynamically allocate an array of that size
(array of student/score structures)."
I then need to, "Call a function to input the student name/score pairs and store them in the array."
So should I create the array in main or inside of the function? How can I return/pass the *array without messing up memory allocation?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Student
{
string name; //student's name
int score; //student's score
};
//function prototypes
void inputNameScore(Student*, int&);
void sortArray(Student* , int);
double avgScore(Student* , int);
void displayTable(Student* , int, double);
int main()
{
Student* arrayOfStudentPtr; //pointer of type student to receive returned array pointer
int numberOfStudents; //number of students to be entered by user
double average; //total score average
cout << "Please enter the number of students: ";
cin >> numberOfStudents;
arrayOfStudentPtr = new Student[numberOfStudents]; //dynamic array of type Student assigned to pointer
inputNameScore(arrayOfStudentPtr, numberOfStudents);
sortArray(arrayOfStudentPtr, numberOfStudents);
average = avgScore(arrayOfStudentPtr, numberOfStudents);
displayTable(arrayOfStudentPtr, numberOfStudents, average);
return 0;
}
void inputNameScore(Student* arrayOfStudentPtr, int& numberOfStudents)
{
for (int i = 0; i < numberOfStudents; i++)
{
cout << endl << "Enter the name for student " << i + 1 << ": ";
cin.ignore();
getline(cin, arrayOfStudentPtr[i].name);
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
while (arrayOfStudentPtr[i].score > 105 || arrayOfStudentPtr[i].score < 0)
{
cout << "Student's score can't be negative or greater than 105." << endl;
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
}
}
}
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}
double avgScore(Student* arrayOfStudentPtr, int numberOfStudents)
{
int total; //total of all grades
double average; //average of all grades
total = 0;
for (int i = 0; i < numberOfStudents; i++)
{
total = arrayOfStudentPtr[i].score;
}
average = total / numberOfStudents;
//average = static_cast<double>(total) / numberOfStudents;
return average;
}
void displayTable(Student* arrayOfStudentPtr, int numberOfStudents, double average)
{
cout << endl << setw(31) << left << "Name" << setw(6) << right << "Score" << endl;
cout << "-------------------------------------" << endl;
for (int i = 0; i < numberOfStudents; i++)
{
cout << setw(31) << left << arrayOfStudentPtr[i].name << setw(6) << right << arrayOfStudentPtr[i].score << endl;
}
cout << "-------------------------------------" << endl;
cout << setw(31) << left << "Average: " << setw(6) << right << endl;
}
The following code will work.
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents-1; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}

How to pass a pointer to an array from main to a function?

Basically, I'm trying to set the size of my array according to an input (numArraySize will be asked for from the user). I created an array pointer in main and want to pass this pointer to the functions.
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int *numbers = new int[numArraySize];
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
return 0;
}
EDIT:
Ok i fixed the error. I changed:
"int numArraySize=1;"
and the position of
"int *numbers = new int[numArraySize];"
The problem was that i had to initialize the numArraySize anyways. That causes error apparently. And the second problem was i have to input numArraySize before i initialize
"int *numbers" in the main function.
#include <iostream>
using namespace std;
// Algorithm for Insertion Sort
int numArraySize=1;
void inputNums(int numArray[])
{
cout << "Enter a bunch of numbers: " ;
for(int x=0; x<numArraySize; x++)
{
cin >> numArray[x];
}
}
void outputNums(int numArray[])
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
void insertionSort(int numArray[])
{
int num;
int i;
for(int j=1; j<numArraySize; j++)
{
num = numArray[j];
i = j-1;
while(i>=0 && numArray[i] > num)
{
numArray[i+1] = numArray[i];
i--;
}
numArray[i+1] = num;
}
}
int main()
{
int choice;
cout << "1) Insertion Sort" << endl;
cout << "Enter your choice: " << endl;
cin >> choice; // Input choice for which algorithm to use
if(choice == 1)
{
cout << "Enter size of the array: ";
cin >> numArraySize;
int *numbers = new int[numArraySize];
inputNums(numbers); // Insert numbers
insertionSort(numbers); // Use algorithm to sort then output
outputNums(numbers);
}
cout << endl;
system("pause");
return 0;
}
Thanks for your helps :)
To pass an array to a function, you can simply use int *array:
void outputNums(int *numArray)
{
for(int x=0; x<numArraySize; x++)
{
cout << numArray[x];
if(x != numArraySize-1)
{
cout << " - ";
}
}
}
Please note that it would be better to use a standard container like a vector.
When you are allocating the memory for the array in line
int *numbers = new int[numArraySize]
, you still haven't received the desired size for the array in variable numArraySize.

for loop character printing [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
.....................HEY GUYS,I GOT THE ANSWER.PLEASE CHECK OUT AT BOTTOM.....................
ThAnKs FoR aLl ThOsE wHo TrYiNg tO hElP mE!
How to print all the character outside the for-loop that input inside for-loop? It only prints the last character entered in for-loop
input all 4 names of items and price in void shop::getdata()
output of this only prints the name of item that entered last in void shop::getdata() for 4 times in void shop::putdata()
output of price is correct,it prints orderly.
what's the problem with the name of item?
Question:WAP to store pricelist of 5 items & print the largest price as well as the sum of all prices & pricelist also.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price[50];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
for(i = 0; i <= 4; i++)
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price[i];
}
}
void shop::putdata()
{
cout << "\t\tPRICE LIST" << "\n";
cout << "\t\t**********" << "\n";
cout << "ITEM NAME\t\t\tPRICE" << "\n";
cout << "*********\t\t\t*****" << "\n";
for(i = 0; i <= 4; i++)
{
cout << item << "\t\t\t\t";
cout << price[i] << "\n";
}
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
sum = sum + price[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = price[0];
for(i = 0; i <= 4; i++)
{
if (price[i] > lar)
lar = price[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x;
int c;
clrscr();
x.getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
x.putdata();
break;
case 2:
x.sum();
break;
case 3:
x.lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
ANSWER
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price;
float e[10];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price;
}
void shop::putdata()
{
cout << item << "\t\t\t\t";
cout << price << "\n";
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
cout<<"Enter prices"<<"\n";
cin>>e[i];
sum = sum + e[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = e[0];
for(i = 0; i <= 4; i++)
{
if (e[i] > lar)
lar = e[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x[10];
int c,i;
clrscr();
for(i=0;i<=4;i++)
x[i].getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
for(i=0;i<=4;i++)
x[i].putdata();
break;
case 2:
x[i].sum();
break;
case 3:
x[i].lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
It's a little hard to tell what you're asking (you would do well to indent your code and ask a clearer question), but I think your problem (well, the main one you're referring to!) is how you're handling item names.
You've declared your shop to contain an array of 50 chars - that is, 50 single characters. Since you have an array of 50 prices, you almost certainly wanted an array of 50 strings. In basic C, that would be char *item[50], an array of 50 dynamically-allocated char arrays. Since you've tagged this as C++, though, you're better off using a string.
A slightly more modern shop would look like this:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::ostream;
using std::string;
using std::vector;
class Item {
string m_name;
double m_price;
public:
Item(const string &name, double price)
: m_name(name), m_price(price) {
};
string name() const { return m_name; }
double price() const { return m_price; }
};
class Shop {
vector<Item> m_items;
public:
void readData();
void writeData() const;
double getPriceSum() const;
double getMaxPrice() const;
};
void Shop::readData() {
for (;;) {
string name, end_of_line;
double price;
cout << "Enter the item name (or nothing to finish input): ";
getline(cin, name);
if (name == "") {
break;
}
cout << "Enter the price: ";
cin >> price;
// the previous ">>" left the end-of-line in the stream,
// so read it now.
getline(cin, end_of_line);
m_items.push_back(Item(name, price));
}
}
void Shop::writeData() const {
for (size_t i = 0; i < m_items.size(); i++) {
const Item &item = m_items[i];
cout << item.name() << "\t" << item.price() << "\n";
}
}
double Shop::getPriceSum() const {
double sum = 0.0;
for (size_t i = 0; i < m_items.size(); i++) {
sum += m_items[i].price();
}
return sum;
}
double Shop::getMaxPrice() const {
double max = 0.0; // assume that all prices are positive
for (size_t i = 0; i < m_items.size(); i++) {
max = std::max(max, m_items[i].price());
}
return max;
}
int main() {
Shop shop;
shop.readData();
shop.writeData();
cout << "sum: " << shop.getPriceSum() << "\n";
cout << "max: " << shop.getMaxPrice() << "\n";
return 0;
}
It is not perfect C++ style, but still makes the code easy to read.