Output does not include all input for my array - c++

I have this program that is barely started:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <string>
using namespace std;
class Grade
{
public:
string studentID;
int userChoice = 0;
int size = 0;
double* grades = new double[size]{0};
};
void ProgramGreeting(Grade &student);
void ProgramMenu(Grade& student);
string GetID(Grade& student);
int GetChoice(Grade& student);
void GetScores(Grade& student);
int main()
{
Grade student;
ProgramGreeting(student);
ProgramMenu(student);
}
// Specification C1 - Program Greeting function
void ProgramGreeting(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << "Welcome to the GPA Analyzer! " << endl;
cout << "By: Kate Rainey " << endl;
cout << "Assignment Due Date: September 25th, 2022 " << endl;
cout << "--------------------------------------------" << endl;
GetID(student);
cout << "For Student ID # " << student.studentID << endl;
}
void ProgramMenu(Grade &student)
{
cout << "--------------------------------------------" << endl;
cout << setw(25) << "Main Menu" << endl;
cout << "1. Add Grade " << endl;
cout << "2. Display All Grades " << endl;
cout << "3. Process All Grades " << endl;
cout << "4. Quit Program." << endl;
cout << "--------------------------------------------" << endl;
GetChoice(student);
}
string GetID(Grade &student)
{
cout << "Enter the student's ID: ";
cin >> student.studentID;
if (student.studentID.length() != 8) {
cout << "Student ID's contain 8 characters ";
GetID(student);
}
return student.studentID;
}
int GetChoice(Grade &student)
{
cout << "Enter your selection: ";
cin >> student.userChoice;
if (student.userChoice == 1) {
GetScores(student);
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 2)
{
}
else if (student.userChoice == 4)
{
exit(0);
}
else
{
cout << "Please enter 1, 2, 3 or 4" << endl;
GetChoice(student);
}
}
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
for (int i = 0; i < student.size; i++) {
student.grades[i] = score;
}
count++;
}
for (int i = 0; i < student.size; i++) {
cout << student.grades[i] << " ";
}
}
I am trying to make sure my array is recording all test scores, but when I output the array in my GetScore function, each element in the array is the same or equal to the last score I entered. For example, if I choose 3 for size and then enter three values of 99.2 86.4 90.1, all three elements will read 90.1.
Why is this happening?

Your Grade class is allocating an array of 0 double elements (which is undefined behavior), and then your GetScores() function does not reallocate that array after asking the user how many scores they will enter, so you are writing the input values to invalid memory (which is also undefined behavior).
Even if you were managing the array's memory correctly (ie, by using std::vector instead of new[]), GetScores() is also running a for loop that writes the user's latest input value into every element of the array, instead of just writing it to the next available element. That is why your final output displays only the last value entered in every element. You need to get rid of that for loop completely.
Try something more like this instead (there are several other problems with your code, but I'll leave those as separate exercises for you to figure out):
class Grade
{
public:
...
int size = 0;
double* grades = nullptr;
};
...
void GetScores(Grade &student)
{
int size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
if (student.size != size) {
delete[] student.grades;
student.grades = new double[size]{0};
student.size = size;
}
for(int i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
for (int i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}
Alternatively:
#include <vector>
...
class Grade
{
public:
...
vector<double> grades;
};
...
void GetScores(Grade &student)
{
size_t size = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# " << student.studentID << "? ";
cin >> size;
student.grades.resize(size);
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades[i] = score;
}
/* alternatively:
student.grades.clear();
for (size_t i = 0; i < size; ++i) {
cout << "Enter a grade: ";
cin >> score;
student.grades.push_back(score);
}
*/
for (size_t i = 0; i < size; ++i) {
cout << student.grades[i] << " ";
}
}

I removed my for loop from my while loop.
void GetScores(Grade &student)
{
int count = 0;
double score = 0;
cout << "How many test scores would you like to enter for ID# "
<< student.studentID << "? ";
cin >> student.size;
while (count != student.size) {
cout << "Enter a grade: ";
cin >> score;
student.grades[count] = score;
count++;
}
for (int j = 0; j < student.size; j++) {
cout << student.grades[j] << " ";
}
}

Related

How do I return the values of the Student Function to Main so that I can I use them for the Display Function?

Program:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Structure
struct Student{
string name;
int pMark;
int eMark;
double avg;
string result;
};
//Functions
Student info(int arrSize, Student arrStudent[10]);
void display(int arrSize, Student arrStudents[10]);
//Main program
int main() {
Student arrStudents[10];
int arrSize;
cout << "How many Students are there(max 10): ";
cin >> arrSize;
info(arrSize, arrStudents);
display(arrSize, arrStudents);
return 0;
}
//Student Function
Student info(int arrSize, Student arrStudent[10]){
int counter = 0;
while(counter < arrSize){
cout << "\nStudent " << (counter + 1) << " info:";
cout << "\nEnter the name: ";
cin >> arrStudent[counter].name;
cout << "Enter the participation mark: ";
cin >> arrStudent[counter].pMark;
cout << "Enter the exam mark: ";
cin >> arrStudent[counter].eMark;
arrStudent[counter].avg = (arrStudent[counter].pMark + arrStudent[counter].eMark) / 2.00;
if (arrStudent[counter].avg >= 50) {
arrStudent[counter].result = "Pass";
}
else {
arrStudent[counter].result = "Fail";
}
counter++;
}
return arrStudent;//(Return Array)?
}
//Display Function
void display(int arrSize, Student arrStudents[10]) {
cout << endl << "Name\t\t Average\t\t Result" << endl;
for (int counter = 0; counter < arrSize; counter++) {
cout << arrStudents[counter].name << "\t\t"
<< fixed << setprecision(2)
<< arrStudents[counter].avg << "\t\t\t"
<< arrStudents[counter].result << endl;
}
}
I tried using the function as such, but I'm not sure if it's correct?
//Student Function
Student info(int arrSize, Student arrStudent[10]){
int counter = 0;
while (counter < arrSize) {
cout << "\nStudent " << (counter + 1) << " info:";
cout << "\nEnter the name: ";
cin >> arrStudent[counter].name;
cout << "Enter the participation mark: ";
cin >> arrStudent[counter].pMark;
cout << "Enter the exam mark: ";
cin >> arrStudent[counter].eMark;
arrStudent[counter].avg = (arrStudent[counter].pMark + arrStudent[counter].eMark) / 2.00;
if (arrStudent[counter].avg >= 50) {
arrStudent[counter].result = "Pass";
}
else {
arrStudent[counter].result = "Fail";
}
counter++;
}
return arrStudent[arrSize];
}
I'm new to coding(In University) so we still need to learn about vectors, pointers and references. That's why I haven't tried any other methods. I would highly appreciate the solutions if it is possible to solve it by avoiding those methods.
You are passing values of array by value, you should pass them by referance, thus you should use pointer,
Example function:
Student info(int arrSize, int *arrStudent)

Keep receiving this error main.cpp:9:91: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘const std::vector’

Sorry in advance if this is lengthy. the problem is within line 9. (where the 2nd cout is.) apparently, but i'm new to this so I can't identify exactly what the issue is.
#include <iostream>
#include <vector>
using namespace std;
void outputRoster(const vector<int> &jersey, const vector<int> &ratings) {
cout << "ROSTER" << endl;
for (int i =1; i < jersey.size(); ++i) {
cout << "Player " << i << " -- Jersey number: " << jersey.at(i-1) << ", Rating: " << ratings << endl;
}
cout << endl;
}
void addPlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter another player's jersey number: ";
cin >> num;
jersey.push_back(num);
cout << "Enter another player's ratings: ";
cin >> num;
cout << endl;
ratings.push_back(num);
}
void removePlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter a jersey number: ";
cin >> num;
cout << endl;
for (int i = 0; i < jersey.size(); ++i){
if (jersey.at(i)==num){
jersey.erase(jersey.begin()+i);
ratings.erase(ratings.begin()+i);
break;
}
}
}
void updatePlayerRating(const vector<int> &jersey, vector<int> &ratings){
int num;
cout << "Enter a jersey number: " << endl;
cin >> num;
for (int i = 0; i < jersey.size(); ++i){
if(jersey.at(i) == num){
cout << "Enter a new rating for player: ";
cin >> num;
cout << endl;
ratings.at(i) = num;
}
}
}
void outputPlayersAboveRating(const vector<int> &jersey, const vector<int> &ratings) {
int num;
cout << "Enter a rating: ";
cin >> num;
cout << endl;
cout << "ABOVE " << num << endl;
for (int i = 0; i < ratings.size(); ++i){
if (ratings.at(i) > num) {
cout << "Player " << i+1 << " -- Jersey number: " << jersey.at(i) << ", Rating: " << ratings.at(i);
}
}
cout << endl;
}
int main() {
vector<int> jersey;
vector<int> ratings;
for (int i = 0; i < 5; ++i) {
int num;
cout << "Enter player " << i+1 << "'s jersey number:";
cin >> num;
jersey.push_back(num);
cout << "Enter player " << i+1 << "'s ratings:";
cin >> num;
ratings.push_back(num);
cout << endl;
cout << endl;
}
outputRoster(jersey, ratings);
char inp;
while(true) {
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "Choose an option: ";
cin >> inp;
cout << endl;
if (inp == 'a') {
addPlayer(jersey, ratings);
}
else if (inp == 'd') {
removePlayer(jersey, ratings);
}
else if (inp == 'u') {
updatePlayerRating(jersey, ratings);
}
else if (inp == 'r') {
outputPlayersAboveRating(jersey, ratings);
}
else if (inp == 'o') {
outputRoster(jersey, ratings);
}
else if (inp == 'q') {
return 0;
}
}
return 0;
}
Any and all help is appreciated also if possible, could you explain how to avoid an error like this in the future.
Thanks in advance.
You cannot print ratings directly in
cout ... << ratings ... because std::vector doesn't have an operator overload for printing. Rather, you have to print out an element inside that vector, so change it to cout ... << ratings[i] ..., which I'm assuming is your desired effect.
This is exactly what the compiler error is telling you. std::vector doesn't have an overload (no operator<< match).

vector compiler error for different variable type

The goal of this assignment for my class is to ask the user for how many students are in the class.
Using the Vector library create a vector of Strings to hold the students names.
Create a vector of type double to hold a students grade average.
I have a couple two compiler errors that are preventing my code from running. Line 73 & 83. The following errors I am given:
main.cpp: In function ‘void add_student()’: main.cpp:73:11: error: request for member ‘push_back’ in ‘grade’, which is of non-class type ‘double’
73 | grade.push_back(grade);
| ^~~~~~~~~
main.cpp: In function ‘void remove_student()’: main.cpp:83:23: warning: comparison of integer expressions of different signedness: ‘int’ and ‘std::vector<std::__cxx11::basic_string<char> >::size_type’ {aka ‘long unsigned int’} [-Wsign-compare]
83 | for (int i = 0; i < students.size(); i++)
| ~~^~~~~~~~~~~~~~~~~**
Any help would be much appreciated. Below is my entire code
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
vector<string> students;
vector<double> grade;
void add_student();
void remove_student();
void menu();
void print_summary();
int main()
{
int numStudent;
char menuSelection;
cout << "Welcome to the Student roaster!" << endl;
cout << "How many students are in your class?:" << endl;
cin >> numStudent;
for (int i = 0; i < numStudent; i++)
{
add_student();
}
cout << "Thank you for entering class information!" << endl;
//calls menu for the user
menu();
while (1)
{
cout << "selection:" << endl;
cin >> menuSelection;
if (menuSelection == 'a')
{
add_student();
}
else if (menuSelection == 'r')
{
remove_student();
}
else if (menuSelection == 'p')
{
print_summary();
}
else if (menuSelection == 'm')
{
menu();
}
else if (menuSelection == 'q')
break;
else
cout << "Not a valid selection" << endl;
}
return 0;
}
void add_student()
{
string firstName, lastName;
double grade;
//ask for student info
cout << "Please enter student (Fisrt Last Grade) info: " << endl;
cin >> firstName >> lastName >> grade;
firstName += " ";
firstName += lastName;
//inserts new student
students.push_back(firstName);
grade.push_back(grade);
}
void remove_student()
{
string first, last;
cout << "Enter the student (First Last) to remove :\n";
cin >> first >> last;
first += " ";
first += last;
int loc = 0;
for (int i = 0; i < students.size(); i++)
{
if (students[i] == first)
{ // finding the location to erase
loc = i;
break;
}
}
students.erase(students.begin() + loc); //removing using erase function
grade.erase(grade.begin() + loc);
}
void menu()
{
cout << "Please choose one of the following options:\n";
cout << "a: add a student\n";
cout << "r: remove a student\n";
cout << "p: print the class summary\n";
cout << "m: print menu\n";
cout << "q: quit program\n";
}
void print_summary()
{
cout << "class summary" << endl;
cout << "--------------------------------" << endl;
cout << "Name" << setw(20) << "Grade" << endl;
cout << "-------" << setw(20) << "--------" << endl;
int n = students.size();
double total = 0;
//cycles through each student
for (int i = 0; i < n; i++)
{
int temp = students[i].size();
int loc = 20 - temp;
cout << students[i] << setw(loc) << grade[i] << endl;
total += grade[i];
}
cout << "Number of students: " << endl;
cout << "------------------" <<endl;
cout << n << " " << endl;
total = (total) / n;
cout << "Average Grade: " << endl;
cout << "--------------" << endl;
//limits the deciaml places to 2
cout << fixed << setprecision(2) << total << " " << endl;
}
The name of the local variable was the same as the name of the global variable.
So you should rename local variable.
62) double grade_;
66) cin >> firstName >> lastName >> grade_;
73) grade.push_back(grade_);

Program gives errors using strings in array

I am creating an employee structure, with an array. However, it keeps returning this error.
The program is supposed to allow the user to enter an id number and validate, which already works. Then it is supposed to allow the user to search for a value inside the array.
#include <iostream>
#include <string.h>
using namespace std;
struct Employee
{
int idNum;
double payRate;
string firstName, lastName;
};
int main()
{
int error;
const int SIZE = 5;
Employee employee[SIZE];
for(int k = 0; k < SIZE; ++k)
{
employee[k].idNum = 0;
employee[k].payRate = 0;
}
for(int count = 0; count < SIZE; ++count)
{
error = 0;
cout << "Enter the employee's id number " << endl;
int tempId;
cin >> tempId;
for (int i = 0; i < SIZE; ++i)
{
if (employee[i].idNum == tempId)
error = 1;
}
while(error == 1)
{
cout << "Invalid entry. Please enter a new id number " << endl;
cin >> employee[count].idNum;
for(int i = 0; i < count; ++i)
{
error = 0;
if(employee[i].idNum == employee[count].idNum)
error = 1;
}
}
cout << "Enter the employee's pay rate " << endl;
cin >> employee[count].payRate;
cout << "Enter the employee's first name " << endl;
cin >> employee[count].firstName;
cout << "Enter the employee's last name " << endl;
cin >> employee[count].lastName;
}
int choice;
cout << "Enter 1 to search for an employee by id number, enter 2 to search by last name, and enter 3 to search by pay " << endl;
cin >> choice;
if(choice == 1)
{
int idNumC;
cout << "Enter an id number ";
cin >> idNumC;
for(int count = 0; count < SIZE; ++count)
{
if(employee[count].idNum == idNumC)
cout << employee[count].idNum;
}
}
if(choice == 2)
{
string name;
cout << "Enter the employee's last name " << endl;
cin >> name;
for(int count = 0; count < SIZE; ++count)
{
if(strcmp(employee[count].lastName, name) == 0)
cout << "ID number: "<< employee[count].idNum << " First name: " << employee[count].firstName << " Last Name: " << employee[count].lastName << " Hourly Pay: " << endl;
}
}
if(choice == 3)
{
int nam;
cout << "Enter the employee's pay rate " << endl;
cin >> nam;
for(int count = 0; count < SIZE; ++count)
{
if(employee[count].payRate == nam)
cout << "ID number: "<< employee[count].idNum << " First name: " << employee[count].firstName << " Last Name: " << employee[count].lastName << " Hourly Pay: " << endl;
}
}
}
I get
76:41: error: cannot convert 'std::string {aka
std::basic_string<char>}' to 'const char*' for argument '1' to 'int
strcmp(const char*, const char*)'
How can I fix this error? Thank you for your time.
You can compare two string with == so i should you if(employee[count].lastName==name) instead of if(strcmp(employee[count].lastName, name) == 0)
But if you want use strcmp try
if(strcmp(employee[count].lastName.c_str(), name.c_str()) == 0)

C++ Out of Bounds Error

I am trying to push a certain struct that exists in my private class into a vector of the class type records. I get the variable data in my main function but for some reason I keep getting an out of bounds error when trying to copy the information into the struct. If you could explain the error in my method of pushing the struct into the class vector that would be great... I included my planned print function as well.
Here's the class :
class students
{
public:
// All necessary member functions here
students(int RUID, string first_name, string last_name, vector<double> quiz_grades, array<double, 3> exam_grades)
{
record records;
records.RUID = RUID;
records.first_name = first_name;
records.last_name = last_name;
for (int i = 0; i < quiz_grades.size(); ++i)
{
records.quiz_grades[i] = quiz_grades[i];
}
for (int i = 0; 0 < 3; ++i)
{
records.exam_grades[i] = exam_grades[i];
}
student_records.push_back(records);
}
void printRecords()
{
//vector<record>::iterator it = student_records.begin(); it != student_records.end(); ++it
for (unsigned int i = 0; i < student_records.size(); ++i)
{
cout << "Ruid: " << student_records[i].RUID << endl;
cout << "First Name: " << student_records[i].first_name << endl;
cout << "Last Name: " << student_records[i].last_name << endl;
for (unsigned int j = 0; j < student_records[i].quiz_grades.size(); ++j)
{
cout << "Quiz grade " << j + 1 << " is: " << student_records[i].quiz_grades[j] << endl;
}
for (int k = 0; k < 3; ++k)
{
cout << "Test grade " << k + 1 << " is: " << student_records[i].exam_grades[k] << endl;
}
}
}
// using the friend function in class
friend void change_name(students stdn); // passing all necessary inputs
private:
struct record
{
int RUID;
string first_name;
string last_name;
vector<double> quiz_grades;
array<double, 3> exam_grades = { 0,0,0 };
};
vector<record> student_records;
};
Here's my main function:
int main()
{
string input;
bool quit = false;
int RUID;
string first;
string last;
double grade = 100;
vector<double> quizG;
array <double, 3> examG = { 0, 0, 0 };
cout << " --'new' to add, 'quit' to end--" << endl;
while (quit != true)
{
cout << "Please enter would you would like to do: ";
cin >> input;
cout << endl;
if (input == "quit")
{
quit = true;
break;
}
if (input == "new")
{
cout << "Please enter the RUID: ";
cin >> RUID;
cout << endl << "Please enter the first name: ";
cin >> first;
cout << endl << "Please enter the last name: ";
cin >> last;
cout << "Enter quiz grades. Enter number less than 0 to stop." << endl;
while (grade >= 0)
{
cout << "Enter quiz grade: ";
cin >> grade;
if (grade >= 0)
{
quizG.push_back(grade);
}
else if (grade < 0)
{
break;
}
}
for (int i = 0; i < 3; ++i)
{
cout << "Please enter " << i + 1 << " test grade: ";
cin >> grade;
examG[i] = grade;
}
}
students stdn(RUID, first, last, quizG, examG);
//stdn.printRecords();
}
// change_name(stdn);
return 0;
In students::students(),
for (int i = 0; 0 < 3; ++i)
// ^^^ should be `i`
is obviously wrong.