Question

we have this given problem to work on which is..

Create a program that would compute for the grade equivalent of two students who just took an exam in Math, Science and English. Your program should consist of two structures: first, struct Subjects that has as its members Math, Science and English in which the grade equivalent of the two students is stored; second, struct Student with members Name, Course, and StudentSub whose type is Subjects.

Use a pointer to store the information for the two different students. After entering the name and course of a student, the user must have a choice of which subject she wants to input a grade first. After the user chooses which subject she wants to put a grade, the user should input the student’s score and the total points of the exam. A separate function should compute for the grade of the student given the score and the total points of the exam.

After entering all information the program must display both the student’s name, course and grades in the different subjects.

Ex:          Name: Sarah

                Course: CS

                Math: 2.5

                English: 2.5

                Science: 2.5  

 

                Name: Mark

                Course: IT

                Math: 2.5

                English: 3

                Science: 2

 

To compute for the grade we must compute for the percent correct first.

 

                Percent Correct = (Score / Highest Possible Score)* 100



And what I did was:

#include <iostream>
#include <string>
using namespace std;


struct Subjects
{
    int math;
    int science;
    int english;

};
struct Student
{
    string name;
    string course;
    string StudentSub;
};

int percent(int a, int b)

    {
        int r;
        r=(a/b)*100;
        return r;
    }

void main()
{    
    int c;
    int score,total;
    char choice;
    Student astud;
    Student *pstud;

    pstud = &astud;

    cout<<"Name :";
    getline(cin,pstud->name);
    cout<<"Course :";
    getline(cin,pstud->course);

    
        cout<<"Choose a subject:"<<endl;
        cout<<"1.Math"<<endl;
        cout<<"2.Science"<<endl;
        cout<<"3.English"<<endl;
        cin>>choice;

        switch(choice)
        {

        case '1' :
        
            cout<<"Math"<<endl;
            cout<<"Score: ";
            cin>>score;
            cout<<"Total Score: ";
            cin>>total;
            c = percent(score,total);
            cout<<"Grade: "<<c<<endl;
            break;
        
        case '2':
        
            cout<<"Science:"<<endl;
            cout<<"Score: ";
            cin>>score;
            cout<<"Total Score: ";
            cin>>total;
            break;
        
        case '3':
        
            cout<<"English:"<<endl;
            cout<<"Score: ";
            cin>>score;
            cout<<"Total Score: ";
            cin>>total;
            break;
        default: 
            cout<<"Try again"<<endl;
        }
}

I got stuck. Specially with the calling of the functions. Can I please get some help? Thank you.

Link to comment
https://www.neowin.net/forum/topic/1267580-i-need-help/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

There are a few problems that I can see. First of all StudentSub should be a Subjects struct, not a string.  Secondly, I would break the program down into logical units such as input and printing. By encapsulating the functionality into distinct functions, you're able to easily process multiple students without code repetition. A student class would be better, but your assignment dictates structs.

This is an example of how you might put it together:

#include <stdlib.h>
#include <string>
#include <iostream>
#include <map>
#include <sstream>
using namespace std;

// Singleton pattern wrapping an id -> enumeration
class SubjectList {
	public:
		typedef enum {MATH, ENGLISH, SCIENCE} Subject;
		static SubjectList* getInstance() {
			if (NULL == singleton)
				singleton = new SubjectList();
			return singleton;
		}
		bool isValidSubject(int id) {
			return list.end() != list.find(id);
		}
		Subject getSubject(int id) {
			return list.at(id).enumeration; 
		}
		int count() {return list.size();}
		void print() {
			map<unsigned int, SubjectType>::iterator iter;
			for (iter = list.begin(); list.end() != iter; iter++)
				cout << iter->first << "." << iter->second.description << endl;
		}			
	private:
		typedef struct {
			Subject enumeration;
			string  description;
		} SubjectType;
		SubjectType makeType(Subject enumeration, string description) {
			SubjectType type = {enumeration, description};
			return type;
		}
		SubjectList() {
			list[1] = makeType(MATH, "Math");
			list[2] = makeType(ENGLISH, "English");
			list[3] = makeType(SCIENCE, "Science");
		}
		static SubjectList* singleton;
		map<unsigned int, SubjectType> list;
};
SubjectList* SubjectList::singleton = NULL;

typedef struct {
	float math;
	float english;
	float science;
} Subjects;

typedef struct {
	string name;
	string course;
	Subjects grades;
} Student;

bool
isValidStudentName(string name) {
	// do student name validation
	return !name.empty();
}
bool
isValidStudentCourse(string course) {
	// validate against list of approved courses
	return !course.empty();
}
float 
calcGrade(int score, int totalPoints) {
	return ((float)score / totalPoints) * 100;
}	
bool 
inputStudent(Student *student) {
	string input;

	cout << "Enter student's name: ";
	getline(cin, input);
	if (!isValidStudentName(input)) {
		cout << "Invalid student name" << endl;
		return false;
	}		
	
	student->name = input;
	cout << "Enter student " << student->name << "'s course: ";
	getline(cin, input);
	if (!isValidStudentCourse(input)) {
		cout << "Invalid course" << endl;
		return false;
	}		

	student->course = input;

	SubjectList* subjects = SubjectList::getInstance();
	for (int i = 0; i < subjects->count(); i++) {
		cout << "Which subject would you like to grade?" << endl;
		subjects->print();	

		int id; 
		getline(cin, input);
		istringstream(input) >> id;
		if (!subjects->isValidSubject(id)) {
			cout << "Invalid subject" << endl;
			return false;
		}
		
		int score, totalPoints;
		cout << "Enter score: ";
		getline(cin, input);
		istringstream(input) >> score;
		cout << "Enter total points of the exam: ";
		getline(cin, input);
		istringstream(input) >> totalPoints;

		float grade = calcGrade(score, totalPoints);
		switch (subjects->getSubject(id)) {
			case SubjectList::MATH:
				student->grades.math = grade;
				break;	
			case SubjectList::ENGLISH:
				student->grades.english = grade;
				break;	
			case SubjectList::SCIENCE:
				student->grades.science = grade;
				break;	
		}			
	}
	
	return true;
}

void
printStudent(Student *student) {
	cout << student->name << endl;
	cout << student->course << endl;
	cout << "Maths: " << student->grades.math << endl;
	cout << "English: " << student->grades.english << endl;
	cout << "Science: " << student->grades.science << endl;
}

int
main (void) {

	Student unus;
	Student duo;
	
	if (!inputStudent(&unus)) {
		cout << "Invalid input for first student!" << endl;
		return EXIT_FAILURE;
	}
	if (!inputStudent(&duo)) {
		cout << "Invalid input for second student!" << endl;
		return EXIT_FAILURE;
	}

	printStudent(&unus);
	printStudent(&duo);
	
	return EXIT_SUCCESS;
}

 

Link to comment
https://www.neowin.net/forum/topic/1267580-i-need-help/#findComment-596961754
Share on other sites

This topic is now closed to further replies.
  • Posts

    • About bloody time. I have got PRs with hundred of files and the Web UI just struggling to even load the pages.
    • I wonder if it was applying secure boot certificates/dbx files?
    • I recently tried edge. It seems a lot better. A lot of the junk in it is gone. It seems less bloated and snappy.
    • Lethal fake phone chargers are still being sold on Amazon and eBay, UK watchdog warns by Paul Hill Credit: Pexels The UK consumer rights organization, Which?, is claiming that “potentially lethal knock-off chargers” are still being sold on online marketplaces seven years after it exposed the danger of these chargers. In its latest investigation, it bought 15 USB phone chargers from several online marketplaces and found they were missing key information, meaning they cannot be legally sold in the UK. Which? bought the 15 chargers from seven online marketplaces. These were Amazon (including Amazon Haul), AliExpress, B&Q Marketplace, Debenhams Marketplace, and eBay. It said that the chargers were so badly made that anyone using them was at risk of electric shock. Over half the chargers also posed fire and explosion risks. Of the chargers purchased, one was a fake Apple USB-C 35W power adaptor charger. To confuse buyers, the box was branded with an Apple logo, but testing found it to be a fake. Further testing picked up arcing sounds after 10 seconds of use, where a current jumps between two parts of the electrical circuit, which can cause fires, explosions, or electric shock. The manufacturers of this particular charger also put modeling clay inside it to make it feel more weighty, robust, and genuine. Not all of the chargers were technically faulty; however, some were missing key packaging, markings, and documentation, meaning they can’t be sold in the UK legally. Which? said that it is now campaigning alongside a coalition of safety groups and businesses for new laws that make online marketplaces responsible for ensuring the safety of products that they choose to list on their websites. It also said the government needs to start using powers under the Product Regulation and Metrology Act, which was adopted last July, to impose safety requirements on online marketplaces via secondary legislation, but so far, there have been delays. No matter what country you are in, be sure to properly research what you are buying and only buy authentic chargers to prevent fires. You can read more about Which?’s research here.
    • Visual Studio finally gets long-awaited feature that developers will love by Usama Jawad Visual Studio Code is Microsoft's popular, lightweight, open-source code editor, it is actually Visual Studio that is the company's flagship integrated development environment (IDE). Although the IDE already offers a boatload of useful features for developers, Microsoft has finally introduced a long-requested capability that will be loved by many. While developers have already been able to create Git pull requests (PRs) directly within Visual Studio for the past couple of years, it had not been possible to review a PR without switching to the browser, until now. Microsoft revealed in December 2025 that it is working on UX that enables developers to do just that, and fast-forward to June 2026, and Visual Studio finally has native capabilities to open and inspect a PR, discuss feedback, and wrap up the review, all without switching to the browser. This integration works for both GitHub and Azure DevOps (including on-prem). Developers have access to multiple surfaces to open a PR, including Git Repository, Git Changes, and the Git menu in Visual Studio. Once you open a PR, all the important details will be immediately visible to you, from where you can navigate to various levels of granularity and branch states, depending on the reviews that you are engaged in. As you would expect, you also get a diff view that enables you to see code changes inline or side-by-side in a separate panel. You can also review commit-by-commit. Additionally, this UX fosters collaboration as you can leave comments, reply to threads, and resolve conversations easily. Naturally, you can also leverage Copilot to apply a code suggestion to fix a potential issue. When you are done, you have the ability to approve, complete, and merge the PR. This is a pretty major feature as it has been requested heavily for the past few years. You can try it out in Visual Studio 2026 version 18.7, made available here recently. Microsoft plans to enhance this experience further in future releases with comment filtering, a timeline of PR activity, and more.
  • Recent Achievements

    • Week One Done
      Timaximus earned a badge
      Week One Done
    • One Month Later
      Timaximus earned a badge
      One Month Later
    • Rookie
      FBSPL went up a rank
      Rookie
    • First Post
      davidbazooked earned a badge
      First Post
    • Week One Done
      davidbazooked earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      499
    2. 2
      PsYcHoKiLLa
      174
    3. 3
      +Edouard
      160
    4. 4
      Steven P.
      84
    5. 5
      ATLien_0
      75
  • Tell a friend

    Love Neowin? Tell a friend!