I am having issues figuring out how to properly display a student's ID, out of 10 students, along with the highest score. For examle, if student 4 had the highest score if would display said student's ID and their score. I would like to add the student's first and last name as well, if possible. My code is as follows:
// HW2.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
using namespace std;
double TestScore(double score);
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int main()
{
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for (int i = 0; i < 10; i++) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
//Calls TestScore function
student[i].testScore = TestScore(student[i].testScore);
}
//Displays student ID and score v code that I need help on
//cout <<student[i].studentID << " has the highest score, which is "<< TestScore;
}
double TestScore(double score)
{
double newScore = 0;
//Determines student with highest score
for (int n = 0; n < 10; n++) {
if (score > newScore)
{
newScore = score;
}
}
return newScore;
}
It needs to :
1) read the students’ data into the array.
2) find the highest test score.
3) print the names of the students having the highest test score.
Your TestScore function doesn't really do anything. I've modified your code to have a function which returns the index of the student with the best score. Using this index, you can then access that element of the array, and print out its details.
#include <iostream>
using namespace std;
struct studentType {
string studentFName;
string studentLName;
double testScore;
int studentID;
double highScore;
};
int getBestStudent( studentType student[10] );
int main() {
// # of students
studentType student[10];
// For loop to get user input for the 10 students
for ( int i = 0; i < 10; i++ ) {
cout << "Student ID: ";
cin >> student[i].studentID;
cout << "Student First Name: ";
cin >> student[i].studentFName;
cout << "Student Last Name: ";
cin >> student[i].studentLName;
cout << "Student's Test Score: ";
cin >> student[i].testScore;
cout << endl;
}
// Displays student ID and score v code that I need help on
int best = getBestStudent( student );
cout <<student[best].studentFName << " " << student[best].studentLName << " has the highest score, which is "<< student[best].testScore;
}
int getBestStudent( studentType student[10] ) {
int best = 0;
//Determines student with highest score
for ( int n = 1; n < 10; n++ ) {
if ( student[n].testScore > student[best].testScore ) {
best = n;
}
}
return best;
}```
Related
#include <iostream.h>
#include <conio.h>
class Employee{
int Id;
string Name;
string Post;
public:
long int Salary;
void GetDetails();
void DisplayDetails();
friend void MaxSalary();
};
void Employee::GetDetails(){
cout << "\nEnter Employee Id : ";
cin >> Id;
cout << "\nEnter Employee Name : ";
cin.ignore();
getline(cin,Name);
cout << "\nEnter Employee Post : ";
cin.ignore();
getline(cin,Post);
cout << "\nEnter Employee Salary : ";
cin >> Salary;
}
void Employee::DisplayDetails(){
cout << "\nEmployee Id : " << Id;
cout << "\nEmployee Name : " << Name;
cout << "\nEmployee Post : " << Post;
cout << "\nEmployee Salary : " << Salary;
}
void MaxSalary(Employee a[], int x){
long int max;
for(int j=0; j<x; j++){
if(a[j].Salary>a[j+1].Salary)
max=a[j].Salary;
}
cout<<"Maximum Salary = "<<max<<endl;
}
int main()
{
int n, i;
cout<<"Enter Number of Employees : ";
cin>>n;
Employee E[n];
cout<<"\n\n----------ENTER DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Enter details of Employee "<<i+1<<endl;
E[i].GetDetails();
}
cout<<"\n\n----------DETAILS OF EMPLOYEES----------\n\n";
for(i=0;i<n;i++){
cout<<"\n\n Details of Employee "<<i+1<<endl;
E[i].DisplayDetails();
}
MaxSalary(E[n], n );
return 0;
}
There are lots of defects in the given code:
The variable length arrays (VLAs) are not allowed in C++. In other words, the syntax:
cin >> x;
Employee emp[x];
is invalid. Note that C99 is an exception in this case.
In the For loop of MaxSalary(), a[j + 1] is given, it will access out-of-bounds array, which invokes an undefined behavior.
Declaring a variable in a class as public breaks the rule of OOP:
public:
long int Salary; // Not a good idea
You do not need to pass [n] as the function argument:
MaxSalary(E[n], n);
The refined code would look like:
#include <iostream>
#include <limits>
#include <vector>
// Using this statement in order to reduce the spam of 'std::' here
using namespace std;
class Employee {
int ID;
string name;
string post;
long int salary;
public:
Employee() {}
// Initializing the class object
void initEmployee(int id, string varName, string varPost, long sal) {
ID = id, \
name = varName, \
post = varPost, \
salary = sal;
}
// 'salary' getter
long getSalary() {
return salary;
}
// The friend function
friend void maxSalary(vector<Employee> data) {
int max = 0;
for (size_t i{1}, len = data.size(); i < len; i++)
// Comparison
if (data[i].getSalary() > data[i - 1].getSalary())
max = data[i].getSalary();
// After the loop execution, prints the maximum salary
std::cout << "Maximum salary: " << max << endl;
}
};
int main(void) {
int total;
cout << "Enter the total number of employees: ";
cin >> total;
vector<Employee> emp(total);
for (int i{}; i < total; i++) {
// Temporary variables to store data in each iteration
Employee temp;
string tempName;
string tempPost;
int tempID;
long int tempSal;
cout << "Name of the employee " << i + 1 << ": ";
getline(cin, tempName);
// Clearing the 'cin' in order to prevent the getline skips
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Post of the employee: ";
getline(cin, tempPost);
cout << "Employee ID: ";
cin >> tempID;
cout << "Total salary: ";
cin >> tempSal;
// Initializing the temporary object
temp.initEmployee(tempID, tempName, tempPost, tempSal);
// Pushing the object into the main vector
emp.push_back(temp);
}
// Comparing the vector elements (note: it is a friend function)
maxSalary(emp);
return 0;
}
As a test case:
Enter the total number of employees: 2 // Number of employees
Name of the employee 1: John Doe // Employee 1
Post of the employee: Manager
Employee ID: 100
Total salary: 15000
Name of the employee 2: Max Ville // Employee 2
Post of the employee: Assitant Manager
Employee ID: 102
Total salary: 50000
Maximum salary: 50000 // Maximum salary
The final result cannot be displayed.
/*A Teacher has five students who have taken four tests. The teacher uses the following grading scale to assign a letter grade to a student, based on the average of his or her four test scores:
90-100 A
80-89 B
70-79 C
60-69 D
0-59 F
Write a program that uses an array of string objects to hold the five students' names, an array of five characters to hold the five students' letter grades, and five arrays of four doubles each to hold each student's set of test scores. enter code here
The program should allow the user to enter each student's name, and his or her four test scores. It should then calculate and display each student’s average test score, and a letter grade based on the average.
Input Validation: Do not accept test scores less than zero or greater than 100.*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int SUBJECT=4,STUDENT=5;
string name[5];
char grade[5];
double score[SUBJECT][STUDENT];
double average[5];
int i,j,k,l;
for (k=0;k<STUDENT;k++)
{
cout<<"Enter the name of student "<<k+1<<":"<<endl;
getline(cin,name[k]);
}
for (i=0;i<STUDENT;i++)
{
double sum=0;
for (j=0;j<SUBJECT;j++)
{
cout<<"Enter the test scores of subject "<<j+1<<" for "<<name[i]<<":";
cin >> score[i][j];
while (score[i][j] < 0||score[i][j] > 100)
{
cout<<"Invalid test score! Test scores can't be less than 0 or greater than 100."<<endl;
cout<<"Enter again the test scores of subject "<<j+1<<":";
cin >> score[i][j];
}
sum+=score[i][j];
average[i]=sum / SUBJECT;
}
}
cout<<setw(30)<<"Student's name"<<setw(25)<<"Average test score"<<setw(15)<<"Letter Grade"<<endl;
cout<<"------------------------------------------------------------------------------------------"<<endl;
for (l=0;l<STUDENT;l++)
{
if (average[l]>=90)
{
grade[l]='A';
}
else if (average[l]<90 && average[l]>=80)
{
grade[l]='B';
}
else if (average[l]<80 && average[l]>=70)
{
grade[l]='C';
}
else if (average[l]<70 && average[l]>=60)
{
grade[l]='D';
}
else
{
grade[l]='F';
}
cout<<setw(30)<<name[l]<<setw(25)<<average[l]<<setw(9)<<grade[l];
}
return 0;
}
The final result name,average and grade did not be displayed before the program terminated.
There are several issues in your code :
In this line cin >> score[i][j]; , i is related to a student and j is related to a subject, while the declaration was score[SUBJECT][STUDENT]
the average must be calculated after the subject loop
you should avoid magic constants, like in name[5]
It is better to avoid using namespace std;
It is better to better encapsulate variables such as i, j, and therefore not to declare them as global
This is a working example. Note that the final output still needs to be optimised but I let you do it!
#include <iostream>
#include <iomanip>
#include <string>
//using namespace std;
int main()
{
const int SUBJECT = 4,STUDENT = 5;
std::string name[STUDENT];
char grade[STUDENT];
double score[STUDENT][SUBJECT];
double average[STUDENT];
for (int i = 0; i < STUDENT;i++)
{
std::cout << "Enter the name of student " << i+1 << " : " << std::endl;
getline (std::cin,name[i]);
}
for (int i = 0; i < STUDENT; i++)
{
double sum = 0;
for (int j = 0; j < SUBJECT; j++)
{
std::cout << "Enter the test scores of subject "<<j+1<<" for "<<name[i]<<": ";
std::cin >> score[i][j];
while (score[i][j] < 0||score[i][j] > 100)
{
std::cout<<"Invalid test score! Test scores can't be less than 0 or greater than 100." << "\n";
std::cout<<"Enter again the test scores of subject " << j+1 << ": ";
std::cin >> score[i][j];
}
sum += score[i][j];
}
average[i] = sum / SUBJECT;
}
std::cout << std::setw(30) << "Student's name" << std::setw(25) << "Average test score" << std::setw(18) << "Letter Grade" << "\n";
std::cout<<"------------------------------------------------------------------------------------------" << "\n";
for (int i = 0;i < STUDENT; i++)
{
if (average[i]>=90)
{
grade[i]='A';
}
else if (average[i]<90 && average[i]>=80)
{
grade[i]='B';
}
else if (average[i]<80 && average[i]>=70)
{
grade[i]='C';
}
else if (average[i]<70 && average[i]>=60)
{
grade[i]='D';
}
else
{
grade[i]='F';
}
std::cout<<std::setw(30)<<name[i]<<std::setw(25)<<average[i]<<std::setw(20)<<grade[i]<<"\n";
}
return 0;
}
How about adding a <<endl statement to the last cout expression. This should flush the internal buffer to the output.
Recently in my c++ class we have learned about pointers and classes.
I'm trying to make a program that has a class Student, which we will point to give each student a name and test score.
After entering both name and test score, they are sorted and then listed in order of highest to lowest.
I believe all my syntax to be correct, however I am still learning. The problem I am having is that the first time I use my class I get an uninitialized local variable error, any help on how to fix this?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <array>
using namespace std;
class Student {
private:
double score;
string name;
public:
void setScore(double a) {
score = a;
}
double getScore() {
return score;
}
void setName(string b) {
name = b;
}
string getName() {
return name;
}
};
void sorting(Student*, int);
int main()
{
Student *students;
string name;
int score;
int *count;
count = new int;
cout << "How many students? ";
cin >> *count;
while (*count <= 0) {
cout << "ERROR: The number of students must be greater than 0.\n";
cin >> *count;
}
for (int i = 0; i < *count; i++) {
cout << "Please enter the students name: ";
cin >> name;
students[i].setName(name);
cout << "Please enter " << students[i].getName() << "'s score: ";
cin >> score;
while (score < 0) {
cout << "ERROR: Score must be a positive number.\n";
cin >> score;
}
students[i].setScore(score);
}
sorting(students, *count);
for (int i = 0; i < *count; i++) {
cout << students[i].getName() << ": " << students[i].getScore() << endl;
}
system("PAUSE");
return 0;
}
void sorting(Student *s, int size) {
for (int i = 0; i < size; i++) {
for (int j = i; j < size; j++) {
if (s[j].getScore() > s[(j + 1)].getScore()) {
int tmp = s[(j + 1)].getScore();
s[(j + 1)].setScore(s[j].getScore());
s[j].setScore(tmp);
string tmp1 = s[(j + 1)].getName();
s[(j + 1)].setName(s[j].getName());
s[j].setName(tmp1);
}
}
}
}
First off, your Student class can be simplified to this:
struct Student {
double score;
std::string name;
};
Because the accessors do absolutely nothing. I've also added the std:: prefix because using namespace std is considered a bad practice.
Now, instead of using the pointer to store the students, include vector and use that:
std::cout << "How many students? ";
int count;
std::cin >> count;
std::vector<Student> students(count);
The loading routine can also be simplified given the absence of accesors:
for (auto& student : students) {
std::cout << "Please enter the students name: ";
std::cin >> student.name;
std::cout << "Please enter " << student.name << "'s score: ";
std::cin >> student.score;
while (score < 0) {
std::cout << "ERROR: Score must be a positive number.\n";
std::cin >> student.score;
}
}
And actually once you have that, you could just put it in istream& operator>>(istream&, Student&) and reduce it to:
std::copy_n(std::istream_iterator<Student>(std::cin), students.size(), students.begin());
No need now for temporary variables anymore (and even if you want to use them, they should be defined just before the use, so inside of the loop).
The last thing is your sorting routine. First off, there's std::sort that you can use instead if you simply provide a comparator:
std::sort(
begin(students),
end(students),
[](Student const& a, Student const& b) { return b.score < a.score; }
);
If you insist on writing the sorting routine yourself, at least use std::swap.
Hello I've ran into some trouble creating a GroceryItem class and using functions to accept and set input from a user.
Currently when I run the dataEntry function, the compiler moves on to the next function before accepting input from the first function.
I've created a test milk object to test my code but It doesn't allow me to enter data before moving to the next input prompt.
Once I can figure out the class functions, I will also create an array of objects and input values for such.
Any advice for how I can go about fixing this class and functions would be greatly appreciated!
#include <iostream>
using namespace std;
class GroceryItem{
private: int stockNumber;
double price = 0.0;
int quantity;
double totalValue;
double setPrice();
int setStockNum();
int setQuantity();
void setTotalValue();
public:
void dataEntry();
void displayValues();
};
int GroceryItem::setStockNum(){
int stock = 0;
cout << "Enter the stock number for the grocery item: ";
do {
cout << "Stock Number(1000-9999): ";
cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));
stockNumber = stock;
return stockNumber;
}
double GroceryItem::setPrice(){
double x = 0.0;
cout << "Enter the price of the item: ";
while (!(x > 0)) {
cout << "Please enter a positive number for price!";
cin >> x;
}
price = x;
return price;
}
int GroceryItem::setQuantity(){
int x = 0;
cout << "Enter the quantity in stock: ";
while (!(x > 0)){
cout << "Please enter a positive number for quantity!";
cin >> x;
}
quantity = x;
return quantity;
}
void GroceryItem::setTotalValue(){
totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
setStockNum();
system("pause");
setPrice();
system("pause");
setQuantity();
system("pause");
setTotalValue();
}
void GroceryItem::displayValues(){
cout << "Stock number: " << stockNumber;
cout << "\nItem price: " << price;
cout << "\nQuantity on hand: " << quantity;
cout << "\nTotal value of item: " << totalValue;
}
int main(){
GroceryItem Milk;
Milk.dataEntry();
Milk.displayValues();
system("pause");
return 0;
}
Dude, pay attention to the condition of the while statement, the line
!(stock >= 1000 || stock <= 9999)
returns true for stock = 0 (always true, in this case), so the program won't enter the loop.
Maybe you meant something like:
!(stock >= 1000 && stock <= 9999)
AND(&&) not OR(||)
I am working on a grade book project that has 5 students that I want to read the names in for and then with an inner loop grab 4 grades for each student. Something is not working on this loop. This what I am getting:
Please enter the name for student 1: Dave
Please enter the grade number 1 for Dave: 100
Please enter the grade number 2 for Dave: 100
Please enter the grade number 3 for Dave: 100
Please enter the grade number 4 for Dave: 10
Please enter the name for student 2: James
Please enter the grade number 5 for James: 100
Please enter the name for student 3: Sam
Please enter the grade number 5 for Sam: 100
Please enter the name for student 4: Jack
Please enter the grade number 5 for Jack: 100
Please enter the name for student 5: Mike
Please enter the grade number 5 for Mike: 100
It should grab 4 grades before it jumps to the next student. I have not been able to figure this out for the last couple hours. Here is the code I have so far:
#include <iostream>
#include <string>
using namespace std;
const int STUDENTS = 5; //holds how many students we have
const int SCORES = 4;
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS);
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
getNames(names, student1, student2, student3, student4, student5, SCORES, STUDENTS);
// Make sure we place the end message on a new line
cout << endl;
// The following is system dependent. It will only work on Windows
system("PAUSE");
return 0;
}
void getNames(string names[], double student1[SCORES], double student2[SCORES],
double student3[SCORES], double student4[SCORES], double student5[SCORES], int SCORES, int STUDENTS)
{
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
if (i == 0)
{
int count1 = 0;
for (count1; count1 < SCORES; count1++)
{
cout << "Please enter the grade number " << count1+1 << " for " << names[i] <<": ";
cin >> student1[count1];
cout << endl;
}
}
else if (i == 1)
{
int count2 = 0;
for (count2; count2 < SCORES; count2++);
{
cout << "Please enter the grade number " << count2+1 << " for " << names[i] <<": ";
cin >> student2[count2];
cout << endl;
}
}
else if (i == 2)
{
int count3 = 0;
for (count3; count3 < SCORES; count3++);
{
cout << "Please enter the grade number " << count3+1 << " for " << names[i] <<": ";
cin >> student3[count3];
cout << endl;
}
}
else if (i == 3)
{
int count4 = 0;
for (count4; count4 < SCORES; count4++);
{
cout << "Please enter the grade number " << count4+1 << " for " << names[i] <<": ";
cin >> student4[count4];
cout << endl;
}
}
else
{
int count5 = 0;
for (count5; count5 < SCORES; count5++);
{
cout << "Please enter the grade number " << count5+1 << " for " << names[i] <<": ";
cin >> student5[count5];
cout << endl;
}
}
}
}
Thanks for any help on this!
There's some pretty rough stuff going on in here, but the problem is that you have a semi-colon on all your inner loops except the first one:
for (count2; count2 < SCORES; count2++);
Remove the semi-colon, and the stuff in the braces will become part of the loop.
I'm going to suggest you make your code a little tidier and less error-prone by chucking all those function arguments into their own array when you enter the function, like this:
double *scores[5] = { student1, student2, student3, student4, student5 };
Then you take OUT all that repetition - the copy/paste is what caused your problems to begin with:
for (int i = 0; i < STUDENTS; i++)
{
cout << "Please enter the name for student " << i+1 << ": ";
cin >> names[i];
cout << endl;
for (int s = 0; s < SCORES; s++)
{
cout << "Please enter the grade number " << s+1 << " for " << names[i] <<": ";
cin >> scores[i][s];
cout << endl;
}
}
Why can't you use two nested loops like
for (int studix=0, stduix<STUDENTS; studix++) {
//...
for (int gradix=0; gradix<SCORE; gradix++) {
//...
}
//....
}
BTW, the condition could be a more complex one, e.g. with the internal loop being
bool goodgrade=true;
for (int gradix=0; goodgrade && gradix<SCORE; gradix++) {
// you could modify goodgrade or use break; inside the loop
}
Don't forget the possible use of continue and break inside a loop.
And please, take time to read some good C++ programming book
Building on Basile's answer and my comments:
int main()
{
string names[STUDENTS] = {""};
char grades[STUDENTS] = {""};
double student1[SCORES] = {0};
double student2[SCORES] = {0};
double student3[SCORES] = {0};
double student4[SCORES] = {0};
double student5[SCORES] = {0};
double *gradeArray[STUDENTS];
gradeArray[0] = student1;
gradeArray[1] = student2;
gradeArray[2] = student3;
gradeArray[3] = student4;
gradeArray[4] = student5;
for (int studix=0, stduix<STUDENTS; studix++) {
// get the name of the student
for (int gradix=0; gradix<SCORE; gradix++) {
// put the grades in gradeArray[studix][gradix]...
}
//....
}
Yes, I know about 2 D arrays, but I am trying to make explicit how this can be done with "five individual arrays". Clumsy, but I believe this works.