C++ Printing the member who got the highest in a result - c++

This is a problem given to me by my computer mentor and I am trying to explain the problem in simple words(I must remind you that my mentor has only taught me loops array structure. I cannot use class for this problem)
Take two matrix
Print the name of n students in one matrix
Print the id, marks in 5 subject of the students in another 2d
matrix (n*6)
Find the student who got the highest in the total of 5 subject and
print the student name with marks of each subject and his total
marks.(i think we have to us a structure)
For example: The highest marks is secured by :
Name;
id no;
marks in sub 1;
marks in sub 2;
marks in sub 3;
marks in sub 4;
marks in sub 5;
total;
Then print the id and the name of the student who got highest in
each subject
For example:
Subject 1 ID name
Subject 2 ID name .....
I have being able to solve it fully till point (3). but unable to print the person who got the highest in each subject ; and I am facing problem to print the person who got highest in each subject as I have to use many variables(I'm not using structure)
What I have tried so far:
#include <iostream>
using namespace std;
int main()
{
//making 1st array to print the names of the students
char x[500][1000];
int num, i;
cout << "Enter the number of student's data you want to input" << endl;
cin >> num;
cout << endl;
cout << "NAME LIST" << endl;
cout << endl;
for(i = 0; i < num + 1; i++)
{
cin.getline(x[i], 1000);
}
//making a 2nd array to print the id, marks in 5 subjects of the students
int y[num][6];
int a, b;
cout << endl;
cout << endl;
cout << "DETAILS OF THE STUDENT" << endl;
cout << endl;
for(int a = 0; a < num; a++)
{
cout << "ID no of student " << a + 1 << ":";
cin >> y[a][0];
cout << "Marks in subject 1:";
cin >> y[a][1];
cout << "Marks in subject 2:";
cin >> y[a][2];
cout << "Marks in subject 3:";
cin >> y[a][3];
cout << "Marks in subject 4:";
cin >> y[a][4];
cout << "Marks in subject 5:";
cin >> y[a][5];
cout << endl;
}
cout << endl;
cout << "The data you inputed:";
cout << endl;
for(a = 0; a < num; a++)
{
for(b = 0; b < 6; b++)
{
cout << y[a][b] << " ";
}
cout << endl;
}
cout << endl;
cout << endl;
//finding the member who got the highest marks
int s = 0;
int largestSum = 0;
for(a = 0; a < num; i++)
{
for(b = 0; b<6; b++)
{
s += y[a][b];
}
// check to see if we have computed a new larger sum and save it if we have.
if(s > largestSum)
{
largestSum = s;
}
}
cout << "largest sum: " << largestSum << endl;
return 0;
}

int s = 0; <- s needs to be reset to zero in each loop
int largestSum = 0;
for(a = 0; a<num; i++) <- loop doesn't break
{
for(b = 0; b<6; b++) <- b should start at 1
{
s += y[a][b];
}
if(s > largestSum)
{
largestSum = s;
}
}
i is incremented while a remains constant and the loop goes forever.
s is not reset to zero, so you sum all the values.
The first index at b = 0 is supposed to be student id, it should be skipped. Try instead:
int largestSum = 0;
for(a = 0; a < num; a++)
{
int s = 0;
for(b = 1; b < 6; b++)
s += y[a][b];
if(s > largestSum)
largestSum = s;
}

Here's something to go off of.
Note that I only made one matrix and put the Student objects in it.
#include <ctime>
#include <iostream>
#include <string>
#include <vector>
const std::vector<std::vector<std::string>> names = {
{"Ralph", "Gerald", "Henry", "Jessica", "Bob"},
{"Tara", "Tami", "Mike", "Loretta", "Jean"},
{"Jesse", "John", "Carl", "Josh", "Abby"},
{"Carson", "Don", "George", "Hillary", "David"},
{"Micah", "Charlie", "Maximus", "Leonidas", "Xerxes"}
};
int main()
{
time_t seconds;
time(&seconds);
srand((unsigned int)seconds);
struct Subjects
{
unsigned int subject[5] = {};
};
struct Student
{
Subjects sub;
std::string name;
int id;
Student() : name("nobody"), id(-1) {};
Student(const std::string& name, const unsigned int& id) : name(name), id(id) {}
};
Student stud_matrix[5][5] = {};
int count = 0;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].name = names[i][j];
stud_matrix[i][j].id = count;
++count;
}
}
std::cout << "All student names:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].name << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << "All student IDs:\n";
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
std::cout << stud_matrix[i][j].id << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
stud_matrix[i][j].sub.subject[0] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[1] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[2] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[3] = (rand() % 100 + 1);
stud_matrix[i][j].sub.subject[4] = (rand() % 100 + 1);
}
}
Student best_student;
unsigned int highest_grade = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[0];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[1];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[2];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[3];
best_student = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > highest_grade)
{
highest_grade = stud_matrix[i][j].sub.subject[4];
best_student = stud_matrix[i][j];
}
}
}
std::cout << "The highest scoring student in any one subject is: " << best_student.name << std::endl;
std::cout << "ID: " << best_student.id << std::endl;
std::cout << "Marks in sub1: " << best_student.sub.subject[0] << std::endl;
std::cout << "Marks in sub2: " << best_student.sub.subject[1] << std::endl;
std::cout << "Marks in sub3: " << best_student.sub.subject[2] << std::endl;
std::cout << "Marks in sub4: " << best_student.sub.subject[3] << std::endl;
std::cout << "Marks in sub5: " << best_student.sub.subject[4] << std::endl;
std::cout << "Total: " << best_student.sub.subject[0] + best_student.sub.subject[1] + best_student.sub.subject[2] +
best_student.sub.subject[3] + best_student.sub.subject[4] << std::endl;
std::cout << std::endl;
Student stud_sub1;
Student stud_sub2;
Student stud_sub3;
Student stud_sub4;
Student stud_sub5;
unsigned int high_sub1 = {};
unsigned int high_sub2 = {};
unsigned int high_sub3 = {};
unsigned int high_sub4 = {};
unsigned int high_sub5 = {};
for (size_t i = 0; i != 5; ++i)
{
for (size_t j = 0; j != 5; ++j)
{
if (stud_matrix[i][j].sub.subject[0] > high_sub1)
{
high_sub1 = stud_matrix[i][j].sub.subject[0];
stud_sub1 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[1] > high_sub2)
{
high_sub2 = stud_matrix[i][j].sub.subject[1];
stud_sub2 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[2] > high_sub3)
{
high_sub3 = stud_matrix[i][j].sub.subject[2];
stud_sub3 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[3] > high_sub4)
{
high_sub4 = stud_matrix[i][j].sub.subject[3];
stud_sub4 = stud_matrix[i][j];
}
if (stud_matrix[i][j].sub.subject[4] > high_sub5)
{
high_sub5 = stud_matrix[i][j].sub.subject[4];
stud_sub5 = stud_matrix[i][j];
}
}
}
std::cout << "Best of subject:\n";
std::cout << "Subject 1:\nID: " << stud_sub1.id << ' ' << stud_sub1.name << " Score: " << high_sub1 << std::endl;
std::cout << "Subject 2:\nID: " << stud_sub2.id << ' ' << stud_sub2.name << " Score: " << high_sub2 << std::endl;
std::cout << "Subject 3:\nID: " << stud_sub3.id << ' ' << stud_sub3.name << " Score: " << high_sub3 << std::endl;
std::cout << "Subject 4:\nID: " << stud_sub4.id << ' ' << stud_sub4.name << " Score: " << high_sub4 << std::endl;
std::cout << "Subject 5:\nID: " << stud_sub5.id << ' ' << stud_sub5.name << " Score: " << high_sub5 << std::endl;
system("pause");
return 0;
}
Sample Output:
All student names:
Ralph Gerald Henry Jessica Bob
Tara Tami Mike Loretta Jean
Jesse John Carl Josh Abby
Carson Don George Hillary David
Micah Charlie Maximus Leonidas Xerxes
All student IDs:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The highest scoring student in any one subject is: Bob
ID: 4
Marks in sub1: 77
Marks in sub2: 67
Marks in sub3: 7
Marks in sub4: 99
Marks in sub5: 66
Total: 316
Best of subject:
Subject 1:
ID: 23 Leonidas Score: 95
Subject 2:
ID: 18 Hillary Score: 92
Subject 3:
ID: 19 David Score: 98
Subject 4:
ID: 4 Bob Score: 99
Subject 5:
ID: 22 Maximus Score: 98

Related

Numbers being added incorrectly for Flash Card game? Cpp

I am trying to write code that creates a flash card game. Three players draw 3 cards three times. The card score is the total of cards drawn. However, the card score is being added incorrectly. Example from console:
Player 2 wins with a card score of:85
Cards drawn:
11 2 11
11 3 5
11 13 13
If anyone can help me out or explain a better way to do this it would be greatly appreciated.
void FlashCard::drawCards(FlashCard f[3])
{
for (int i =0; i<4;++i)
{
int a = rand() % 13 + 1;
int b = rand() % 13 + 1;
int c = rand() % 13 + 1;
f[0].firstDraw[i] = a;
f[1].firstDraw[i] = b;
f[2].firstDraw[i] = c;
}
for (int i =0; i<4;++i)
{
int a = rand() % 13 + 1;
int b = rand() % 13 + 1;
int c = rand() % 13 + 1;
f[0].secondDraw[i] = a;
f[1].secondDraw[i] = b;
f[2].secondDraw[i] = c;
}
for (int i =0; i<4;++i)
{
int a = rand() % 13 + 1;
int b = rand() % 13 + 1;
int c = rand() % 13 + 1;
f[0].thirdDraw[i] = a;
f[1].thirdDraw[i] = b;
f[2].thirdDraw[i] = c;
}
for (int j = 0;j<3;++j)
{
for(int i = 0;i<3;++i)
{
f[j].cardScore += f[j].firstDraw[i];
}
for(int i = 0;i<3;++i)
{
f[j].cardScore += f[j].secondDraw[i];
}
for(int i = 0;i<3;++i)
{
f[j].cardScore += f[j].thirdDraw[i];
}
}
}
This is how I am outputting the winner.
void FlashCard::printWinner(FlashCard f[3])
{
if (f[0].cardScore > f[1].cardScore && f[0].cardScore > f[2].cardScore)
{
std::cout << "Player 1 wins with a card score of:" << f[0].cardScore<<std::endl;
std::cout << "Cards drawn: " << std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[0].firstDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[0].secondDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[0].thirdDraw[i] << " ";
}
std::cout<<std::endl;
}
if (f[1].cardScore > f[0].cardScore && f[1].cardScore > f[2].cardScore)
{
std::cout << "Player 2 wins with a card score of:" << f[1].cardScore << std::endl;
std::cout << "Cards drawn: " << std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[1].firstDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[1].secondDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[1].thirdDraw[i] << " ";
}
std::cout<<std::endl;
}
if (f[2].cardScore > f[0].cardScore && f[2].cardScore > f[1].cardScore)
{
std::cout << "Player 3 wins with a card score of:" << f[2].cardScore << std::endl;
std::cout << "Cards drawn: " << std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[2].firstDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[2].secondDraw[i] << " ";
}
std::cout<<std::endl;
for(int i = 0;i<3;++i)
{
std::cout << f[2].thirdDraw[i] << " ";
}
std::cout<<std::endl;
}
}

Heap Corruption Detected: after normal block c++ dynamic 2D array

I keep getting this error Heap Corruption Detected: after normal block... It only comes up if I try to deallocate memory of my 2D array examScores using delete[]. I used a for loop to delete each array so I'm confused, is there still a memory leak somewhere? I'm not super familiar with memory management so thank you in advance for any help
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
string getGradeOfExam(double grade, double examAverage) {
if (grade <= (examAverage - 15)) return "E";
if (grade >= (examAverage + 15)) {
return "A";
}
if (grade < (examAverage - 5)) return "D";
if (grade > (examAverage + 5)) return "B";
return "C";
}
string readNextName(ifstream& inputStream) {
string firstName;
string lastName;
inputStream >> firstName;
inputStream >> lastName;
string fullName = firstName + " " + lastName;
return fullName;
}
int readNextExamScore(ifstream& inputStream) {
int examGrade;
inputStream >> examGrade;
return examGrade;
}
int main(int argc, char* argv[]) {
if (argc < 3)
{
cerr << "Please provide name of input and output files";
return 1;
}
cout << "Input file: " << argv[1] << endl;
ifstream in(argv[1]);
if (!in)
{
cerr << "Unable to open " << argv[1] << " for input";
return 2;
}
cout << "Output file: " << argv[2] << endl;
ofstream out(argv[2]);
if (!out)
{
in.close();
cerr << "Unable to open " << argv[2] << " for output";
return 3;
}
int numStudents = 0;
int numExams= 0;
in >> numStudents >> numExams;
string* studentNames = new string[numStudents];
//first value corresponds to a specific student, second value corresponds to a specific exam
int** examScores = new int* [numStudents];
for (int i = 0; i < numExams; ++i) {
examScores[i] = new int[numExams];
}
for (int i = 0; i < numStudents; i++) {
studentNames[i] = readNextName(in);
for (int j = 0; j < numExams; j++) {
examScores[i][j] = readNextExamScore(in);
}
}
//Finds averages of all exams and stores them in an array
double* examAverages = new double[numExams];
for (int i = 0; i < numExams; i++) {
double examAverage = 0.0;
double totalExamScore = 0.0;
for (int j = 0; j < numStudents; j++) {
totalExamScore += examScores[j][i];
}
examAverage = totalExamScore / numStudents;
examAverages[i] = examAverage;
}
double totalExamScore = 0.0;
double totalExamAverage = 0.0;
for (int i = 0; i < numExams; i++) {
totalExamScore += examAverages[i];
}
totalExamAverage = totalExamScore / numExams;
double* studentAverages = new double[numStudents];
for (int i = 0; i < numStudents; i++) {
double studentTotalScore = 0.0;
for (int j = 0; j < numExams; j++) {
studentTotalScore += examScores[i][j];
}
studentAverages[i] = studentTotalScore / numExams;
}
//OUTPUT
out << "Student Scores:" << endl;
for (int i = 0; i < numStudents; i++) {
out << right << setw(6) << studentNames[i] << "\t";
for (int j = 0; j < numExams; j++) {
out << examScores[i][j] << "\t";
}
out << endl;
}
out << endl;
out << "Exam Averages:" << endl;
for (int i = 0; i < numExams; i++) {
out << setw(6) << "Exam " << i + 1 << " average = " << fixed << setprecision(1) << examAverages[i] << endl;
}
out << endl;
out << "Student Exam Grades:" << endl;
for (int i = 0; i < numStudents; i++) {
out << right << setw(6) << studentNames[i] << "\t";
for (int j = 0; j < numExams; j++) {
out << examScores[i][j] << " ";
out << "(" << getGradeOfExam(examScores[i][j], examAverages[j]) << ")\t";
}
out << endl;
}
out << endl;
out << "Exam Grades:" << endl;
for (int i = 0; i < numExams; i++) {
int gradeCount[5] = { 0,0,0,0,0 };
for (int j = 0; j < numStudents; j++) {
if (getGradeOfExam(examScores[j][i], examAverages[i]) == "A") {
gradeCount[0]++;
}
else if (getGradeOfExam(examScores[j][i], examAverages[i]) == "B") {
gradeCount[1]++;
}
else if (getGradeOfExam(examScores[j][i], examAverages[i]) == "C") {
gradeCount[2]++;
}
else if (getGradeOfExam(examScores[j][i], examAverages[i]) == "D") {
gradeCount[3]++;
}
else if (getGradeOfExam(examScores[j][i], examAverages[i]) == "E") {
gradeCount[4]++;
}
}
out << setw(6) << "Exam " << i + 1 << "\t" << fixed << setprecision(1) << examAverages[i] << "\t";
out << gradeCount[0] << "(A)" << "\t";
out << gradeCount[1] << "(B)" << "\t";
out << gradeCount[2] << "(C)" << "\t";
out << gradeCount[3] << "(D)" << "\t";
out << gradeCount[4] << "(E)" << endl;
}
out << endl;
out << "Student final grades:" << endl;
for (int i = 0; i < numStudents; i++) {
out << studentNames[i] << "\t" << studentAverages[i] << "(" << getGradeOfExam(studentAverages[i], totalExamAverage) << ")" << endl;
}
out << "Class Average Score: " << totalExamAverage << endl;
delete[] studentNames;
for (int i = 0; i < numStudents; i++)
{
delete[] examScores[i];
}
delete[] examScores;
delete[] examAverages;
delete[] studentAverages;
return 0;
}
My input file contains the following:
6 8
Cody Coder 84 100 100 70 100 80 100 65
Harry Houdini 77 68 65 100 96 100 86 100
Harry Potter 100 100 95 91 100 70 71 72
Mad Mulligun 88 96 100 90 93 100 100 100
George Washington 100 72 100 76 82 71 82 98
Abraham Lincoln 93 88 100 100 99 77 76 93
This part seems suspicious:
int** examScores = new int* [numStudents];
for (int i = 0; i < numExams; ++i) {
examScores[i] = new int[numExams];
}
The array examScores has numStudents elements, but the upper bound in the for-loop is numExams.
Errors of this kind can be often localized using the Valgrind tool. (It worked in this case.) Check it out.

Problems with a c++ class

I am working on this university project and I have 2-3 issues. I want to get them done 1 by 1.
My first question is about one of my getter/setter functions.
Here are the class's attributes:
I got getters and setters for each attribute of the class, and a view function that shows the attributes of a class object
class Game{
private:
string gameName;
float gamePrice;
int gameNoPlatforms;
string *gamePlatforms;
int gameNoSitesRating;
int *gameRatings;
int gameSales[19];
string gameLaunchers[5];
}
Those 2 are my get/set function for the atribute * string gamePlatforms:
void setGamePlatforms(string *newGamePlatforms, int newGameNoPlatforms)
{
if (this->gamePlatforms != NULL)
{
delete[] this->gamePlatforms;
}
if (newGameNoPlatforms > 0 )
{
this->gameNoPlatforms = newGameNoPlatforms;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = newGamePlatforms[i];
}
}
else cout << "The number of new game platforms can't be negative. "<< endl;
}
string *getGamePlatforms()
{
return this->gamePlatforms;
}
And this is the input that i tried to test on:
int main(){
Game g1;
int noPlatforms = 10;
string*model = new string[noPlatforms];
for (int i = 0; i < noPlatforms; i++)
{
model[i] = "Platform " + to_string(i+10);
}
g1.setGamePlatforms(model, noPlatforms); //-> not working
g1.setGamePlatforms(model, noPlatforms);
cout << g1.getGamePlatforms();
return 0;
}
And for me it is returning a weird value. I think it is an address. What have I done wrong?
Edit: the entire class:
class Game{
private: string gameName;
float gamePrice;
int gameNoPlatforms;
string *gamePlatforms;
int gameNoSitesRating;
int *gameRatings;
int gameSales[19];
string gameLaunchers[5];
public:
// Constructor1 fara parametrii pt game
Game():gameReleaseYear(2000)
{
this->gameName = "Counter-Strike";
this->gamePrice = 20;
this->gameNoPlatforms = 10;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = "Platform" + to_string(i+1);
}
this->gameNoSitesRating = 5;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
this->gameRatings[i] = i + 1;
for (int i = 1; i < 19; i++)
{
this->gameSales[i] = i + 2;
}
for (int i = 1; i < 5; i++)
{
this->gameLaunchers[i] = "Launcher" + to_string(i);
}
this->noGames++; //incrementare nr games
}
// Constructor cu parametrii pt game
Game(string gameNameP, float gamePriceP, int gameNoPlatformsP, string *gamePlatformsP, int gameNoSitesRatingP, int *gameRatingsP, int gameSalesP[19], string gameLaunchersP[5]) :gameReleaseYear(2005)
{
this->gameName = gameNameP;
this->gamePrice = gamePriceP;
this->gameNoPlatforms = gameNoPlatformsP;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
gamePlatforms[i] = gamePlatformsP[i];
}
this->gameNoSitesRating = gameNoSitesRatingP;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
{
gameRatings[i] = gameRatingsP[i];
}
for (int i = 0; i < 19; i++)
{
gameSales[i] = gameSalesP[i];
}
for (int i = 0; i < 5; i++)
{
gameLaunchers[i] = gameLaunchersP[i];
}
}
// Destructor pt game
~Game()
{
if (this->gamePlatforms != NULL)
delete[] this->gamePlatforms;
if (this->gameRatings != NULL)
delete[] this->gameRatings;
noGames--; // decrementare nr games
}
// Functie de afisare pentru game
void view()
{
cout << "For the game: " <<' '<< this->gameName << " we have the following details: " << endl;
cout << endl;
cout << "The release year for the game was: " << this->gameReleaseYear << endl;
cout << endl;
cout << "The game is sold at a full price of: " << this->gamePrice << " euroes" << endl;
cout << endl;
cout << "The number of sites that are rating this game is: " << this -> gameNoSitesRating << " and the ratings are: " << endl;
cout << endl;
for (int i = 0; i < this->gameNoSitesRating; i++)
{ if(this->gameRatings[i]+i >10)
cout << "The no " << i + 1 << " site is rating the game as " << 10 << " stars out of 10 " << endl;
else
cout << "The no " << i+1 << " site is rating the game as " << this->gameRatings[i] << " stars out of 10 " << endl;
}
cout << endl;
cout << "The sales of the game from the release year since now are: " << endl;
for (int i = 1; i < 19; i++)
{
cout << "For the year " << i << " the sales estimate at " << gameSales[i] << " millions" << endl;
}
cout << endl;
cout << "The launchers that support the game are: " << endl;
for (int i = 1; i < 5; i++)
{
cout << gameLaunchers[i] << ' ' << endl;
}
cout << "The game is currently running on " << this->gameNoPlatforms << " number of platforms, and those platforms are: " << endl;
cout << endl;
for (int i = 0; i < this->gameNoPlatforms; i++)
{
cout << this->gamePlatforms[i] << endl;
}
}
// functiile accesor getters
string getGameName()
{
return this->gameName;
}
float getGamePrice()
{
return this->gamePrice;
}
int getGameNoPlatforms()
{
return this->gameNoPlatforms;
}
int getNoSitesRating()
{
return this->gameNoSitesRating;
}
string *getGamePlatforms()
{
return this->gamePlatforms;
}
int *getGameRatings()
{
return this->gameRatings;
}
string *getGameLaunchers()
{
return this->gameLaunchers;
}
//functiile accesor setters
void setGameName(string newGameName) //testat pt input valid si invalid
{ if(newGameName != gameName)
this->gameName = newGameName;
else cout << "This is the actual name of the game, no modify is required.";
}
void setGamePrice(float newPrice) //testat pt input valid si invalid;
{ if(newPrice>0)
this->gamePrice = newPrice;
else cout << "The price can't be negative." << endl;
}
void setGameNoPlatforms(int newNoPlatforms) //testat pentru input valid, input mai mare ca 5 si negativ
{ if(newNoPlatforms>0 && newNoPlatforms <5)
this->gameNoPlatforms = newNoPlatforms;
else cout << "The number of platforms can't be negative and must be less than 5, since this is the maximum number of existing platforms." << endl;
}
void setGameNoSitesRating(int newNoSites) //testat pentru input valid, input negativ, input mai mare decat 15
{ if(newNoSites>0 && newNoSites<15)
this->gameNoSitesRating = newNoSites;
else cout << "The number of sites can't be negative nor greater than 15 since this is the maximum number of sites that our game is rated on." << endl;
}
void setGamePlatforms(string *newGamePlatforms, int newGameNoPlatforms) //testat pt input valid, returneaza adresa
{
if (this->gamePlatforms != NULL)
{
delete[] this->gamePlatforms;
}
if (newGameNoPlatforms > 0 ){
this->gameNoPlatforms = newGameNoPlatforms;
this->gamePlatforms = new string[this->gameNoPlatforms];
for (int i = 0; i < this->gameNoPlatforms; i++)
{
this->gamePlatforms[i] = newGamePlatforms[i];
}
}
else cout << "The number of new game platforms can't be negative. "<< endl;
}
void setGameRatings(int *newGameRatings, int newNoRatings) //testat pt valori valide, testat pt neNoRatings negativ;
{
if (newNoRatings < 0)
cout << "The new number of sites that are rating the game can't be negative";
else {
if (this->gameRatings != NULL)
{
delete[] this->gameRatings;
}
this->gameNoSitesRating = newNoRatings;
this->gameRatings = new int[this->gameNoSitesRating];
for (int i = 0; i < this->gameNoSitesRating; i++)
{
this->gameRatings[i] = newGameRatings[i];
}
}
}
void setGamesSales(int *newSales)
{
if (newSales != NULL)
{
for (int i = 0; i < 19; i++)
{
gameSales[i] = newSales[i];
}
}
else cout << "The sales can't be null." << endl;
}
void setLaucnhers(string *newLaunchers)
{
if (newLaunchers != NULL)
{
for (int i = 0; i < 5; i++)
{
gameLaunchers[i] = newLaunchers[i];
}
}
else cout << "The name of the new launchers can't be null." << endl;
}
//variabile static/const
const int gameReleaseYear;
static int noGames;
};
int Game::noGames = 0;
Try this:
int Game::getNumberOfPlatforms() const
{
return gameNoPlatforms;
}
And print them:
for(int i = 0; i < g1.getNumberOfPlatforms(); ++i)
cout << g1.getGamePlatforms()[i] << endl;

Compare Class Object using bubble sort

Task: Model in OOP a class named Student containing name, surname and the marks from the winter session exams. Display the name of the students who have arrears exams and the first three students in the group.
I have troubles in comparing the marks(first three students).
My code:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
#include<stdio.h>
class Student {
private:
char nume[10];
char prenume[20];
double matematica;
double fizica;
double programare;
public:
Student(char num[10], char pren[20], double mate, double fiz, double progra);
void afis();
void citire_stud();
int restanta();
double media();
};
Student::Student(char num[10] = "", char pren[20] = "", double mate = 0, double fiz = 0, double progra = 0)
{
strcpy(nume, num);
strcpy(prenume, pren);
matematica = mate;
fizica = fiz;
programare = progra;
}
void Student::afis()
{
cout << "Nume: " << nume << endl;
cout << "Prenume: " << prenume << endl;
cout << "Nota la matematica: " << matematica << endl;
cout << "Nota fizica: " << fizica << endl;
cout << "Nota programare: " << programare << endl;
cout << endl;
}
void Student::citire_stud()
{
char num[10];
char pren[20];
double mate, fiz, progra;
cout << "Introduceti numele studentului: " << endl;
cin >> num;
strcpy(nume, num);
cout << "Introduceti preumele studentului: " << endl;
cin >> pren;
strcpy(prenume, pren);
cout << "Introduceti nota la mate studentului: " << endl;
cin >> mate;
matematica = mate;
cout << "Introduceti nota la fizica studentului: " << endl;
cin >> fiz;
fizica = fiz;
cout << "Introduceti nota la programare studentului: " << endl;
cin >> progra;
programare = progra;
}
int Student::restanta() //arrears
{
if (matematica < 5 || programare <5 || fizica < 5)
return 1;
else return 0;
}
double Student::media()
{
double med;
med = (matematica + fizica + programare) / 3;
return med;
}
void main()
{
int cont = 0;
int res[10];
int nr;
cout << "Cati studenti sunt(max 10): "; //How many students
cin >> nr;
Student ob2[10], temp;
for (int i = 0;i < nr;i++)
{
ob2[i].citire_stud();
if (ob2[i].restanta())
{
res[cont++] = i;
}
}
if (cont == 0)
{
cout << "Nu sunt studenti restanti! " << endl;
goto jmp;
}
else
{
cout << "\nStundetii restanti sunt: " << endl;
int i = 0;
int k = 0;
do
{
k = res[i];
ob2[k].afis();
i++;
} while (i != cont);
}
jmp:
cout << "\n\n\n\nStudentii in ordinea medilor sunt: " << endl;
for (int i = 0;i < nr;i++)
{
if (ob2[i].media() < ob2[i + 1].media()) //Not working
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
for (int i = 0;i < nr;i++)
ob2[i].afis();
system("pause");
}
Output: Output
It should be: 9 - 7 - 5
Your bubble sort is broken. A) You need 2 loops. B) you go out of bounds. Change it to something like:
for (int j = 0; j < nr; j++)
{
for (int i = 0;i < nr - 1 ; i++)
{
if (ob2[i].media() < ob2[i + 1].media())
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
}

the arrays won't add up the votes correctly?

I am writing a program that will tally votes from each counties up to 4 for two candidates. Basically it will ask you to add the votes in each counties for each candidate. Then it will tally the votes and display the winner. This mostly works but It won't add up the votes and declare the winner correctly? I suspect it is something wrong with the loop at line 37 to line 40.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[7];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}
Let me know if there is any other revision that I should do!
Thanks!
Your votes array is short.
It seems you have 4x2 entries, but the array is only 7 elements.
Here's a version that I could live with:
Live On Coliru
#include <iostream>
#include <numeric>
using namespace std;
int tier1();
int main(void) {
return tier1();
}
static int getnumber(std::string prompt) {
if (!std::cin)
return 0;
int i;
std::cout << prompt;
std::cin >> i;
while(!std::cin) {
if (std::cin.eof()) {
exit(1);
}
std::cin.clear();
std::cin.ignore(1<<30, '\n');
std::cout << prompt;
std::cin >> i;
}
return i;
}
#include <map>
#include <algorithm>
int tier1() {
using namespace std;
using county = int;
static constexpr int number_of_counties = 4;
static constexpr int number_of_candidates = 2;
map<county, size_t[number_of_candidates]> votes;
for (int cty = 0; cty < number_of_counties; cty++) {
for (int cand = 0; cand < number_of_candidates; cand++) {
votes[cty][cand] = getnumber("How many votes did the candidate " + to_string(cand) + " get in county " + to_string(cty) + "? ");
}
if (std::accumulate(begin(votes[cty]), end(votes[cty]), 0u) > 100)
cout << "County has too many votes. Exiting!\n"; // Print an error
}
size_t totals[number_of_candidates] = { 0 };
for(auto& cty: votes) {
for (auto in = begin(cty.second), accum = begin(totals); accum < end(totals);) {
*accum++ += *in++;
}
}
auto winner = max_element(begin(totals), end(totals));
cout << "The winner of the election is candidate " << distance(totals, winner) << "\n";
cout << "Here is the voting results:\n";
for (int cand = 0; cand < number_of_candidates; cand++) {
cout << "candidate " << cand << " got " << totals[cand] << " votes\n";
}
return 0;
}
In addition to sehe's observation, I also see you have the following:
for (i = 0; i < 7; i++)
{
cout << votes[i+1] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i+1];
candidate1Votes += votes[i+1];
}
This should probably be (after you make your array size 8):
// Loop through all countries
for (i = 0; i < 8; i = i + 2)
{
// Print out the candidate's votes per country
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
Here is an improved suggestion which structures the code in a way that makes more sense (altough my original suggestion is probably easier):
You could use a two dimensional array as follows:
int votes[2][4]; //Store the votes in the format [candidate 0 or 1][country 0 to 3]
The loop in question would then become:
// Loop through all countries
for (i = 0; i < 4; i++)
{
// Print out the candidate's votes per country
cout << votes[0][i] << "\n";
cout << votes[1][i] << "\n";
// Total up each candidate's votes
candidate0Votes += votes[0][i];
candidate1Votes += votes[1][i];
}
The rest of the code would need to be modified to adapt to that structure as well. Since this could be a bit confusing, I left it as a separate answer. It is probably a bit better way to structure the program, but my original answer should fix the problem.
I think this is what you want. The array size was changed to 8, and the for loop in line 37 to 40 was also modified.
#include<iostream>
using namespace std;
int tier1();
int main(void)
{
int return_val = tier1();
if (return_val < 0) // print an error
return 0;
}
int tier1(){
int votes[8];
int i, j, N; // variables
int k = 0;
for (i=0; i<4; i++)
{
cout << "county" << i << "\n"; // lists the 4 counties/candidates
for (j=0; j<2; j++)
{
cout << "How many votes did the candidate " << j << " get?\n";
N=0;
cin >> N;
votes[k++] = N;;
}
if (votes[k-2] + votes[k-1] > 100) //checking if it goes over 100 votes
{
cout << "County has too many votes. Exiting!\n"; // Print an error
exit(1);
}
}
int candidate0Votes = 0; //resetting
int candidate1Votes = 0;
for (i = 0; i < 8; i+=2)
{
cout << votes[i] << "\n";
cout << votes[i+1] << "\n";
candidate0Votes += votes[i];
candidate1Votes += votes[i+1];
}
if (candidate0Votes > candidate1Votes){
cout << "The winner of the election is candidate 0.\n";
}
else
{
cout << "The winner of the election is candidate 1.\n";
}
cout << "Here is the voting results:\n";
cout << "candidate 0 got ";
cout << candidate0Votes;
cout << " votes\n";
cout << "candidate 1 got ";
cout << candidate1Votes;
cout << " votes\n";
return 0;
}