I wish to output different string for reading variables. For example, below, I wish to print Enter english marks before reading english marks using eng.setmarks(). Please suggest a way to implement this.
Here is my code: (look at for loop below)
#include <iostream>
#include <cstring>
using std::cin;
using std::cout;
class student {
char name[20];
int age;
class marks {
int marks;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
};
public:
marks eng, math, phy, chem, cs; // nested objects are public
void setname( char* n) {
strncpy( name, n, 20);
}
char* getname() {
return name;
}
void setage( int a) {
age = a;
}
float total() {
size_t total = eng.getmarks() + math.getmarks() +
phy.getmarks() + chem.getmarks() + cs.getmarks();
return total/500.0;
}
};
int main() {a
student new_stud;
char temp[20];
cout << "Enter name: ";
cin >> temp;
cin.get( temp, sizeof(temp));
new_stud.setname(temp);
int age;
cout << "Enter age: ";
cin >> age;
new_stud.setage( age);
for( size_t i = 0; i < 5; ++i) {
// I wish to output: "Enter marks in" + subject_name, but harcoding it seems tedious
}
cout << "\nTotal Percentage: " << new_stud.total();
return 0;
}
So if I understand correctly, you would like to print out the name of the variable which you are about to read into. Now this can't be done on the way you want it. The best thing you can do is make an array of subject names, and an array of marks.
string[5] Subjects = {"Maths", "English", "Chemistry", "Physiscs", "Computer Sciences"};
marks[5] Marks;
for(int i=0;i<5;i++) {
cout << "Please enter marks in " << Subjects[i] << ":" << endl;
int a;
cin >> a;
Marks[i].setmarks(a);
}
You could also make the marks class have a field subject name, and give it a function inputfromuser(), like this:
class marks {
int marks;
string subjectName;
public:
void setmarks( int x) {
marks = x;
}
int getmarks() {
return marks;
}
void inputfromuser() {
cout << "Please enter marks in " << subjectName << ":" << endl;
cin >> marks;
}
};
Sorry for me using the std::string type, I am not very comfortable with the raw char[] way to handle texts.
Related
I have three C++ class, InventoryItem, SalesPerson and Transaction. I am using composition to use InventoryItem and SalesPerson class in Transaction. I want to use user input instead of just passing values in constructor, but I am not being able to do it. Any help will be highly appreciated. Following is my C++ file.
#include<iostream>
#include<string>
using namespace std;
class InventoryItem {
private:
int stockNum; double price;
public:
InventoryItem(int, double);
void display(); };
InventoryItem::InventoryItem(int stkNum, double pr) {
stockNum = stkNum;
price = pr;
}
void InventoryItem::display() {
cout << "Item #" << stockNum << " costs $" << price << endl;
}
//SalesPerson class
class Salesperson {
private:
int idNum;
string name; public:
Salesperson(int, string); void display();
};
Salesperson::Salesperson(int id, string lastName) {
idNum = id;
name = lastName;
}
void Salesperson::display() {
cout << "Salesperson #" << idNum << " " << name << endl;
}
//Transaction(main class)
class Transaction {
private:
int transNum;
InventoryItem itemSold;
Salesperson seller;
public:
Transaction(int, int, double, int, string);
void display();
};
Transaction::Transaction(int num, int item, double pr,
int salesId, string name) : itemSold(item, pr),
seller(salesId, name) {
transNum = num;
}
void Transaction::display() {
cout << "Data for transaction #" << transNum << endl; itemSold.display();
seller.display();
}
int main() {
Transaction aSale(247, 782, 44.77, 512, "Richardson"); aSale.display();
return 0;
}
I am posting this as an answer instead of comment, because i dont have backticks on my phone. So you want to do something like
int main()
{
int x, y, z;
double f;
string name;
cin >> x >> y >> f >> z >> name;
Transaction(x, y, f, z, name);
return 0;
}
Of course you can divide the cin line into one cin per variable and cout instructions on what a user must input next. This would look like this
int main()
{
int x, y, z;
double f;
string name;
cout << "Enter x: ";
cin >> x;
cout << "Enter y: ";
cin >> y;
cout << "Enter f: ";
cin >> f;
cout << "Enter z: ";
cin >> z;
cout << "Enter name: ";
cin >> name;
Transaction(x, y, f, z, name);
return 0;
}
Substitute strings in cout lines with strings you want to prompt the user with.
Throwing this out there first I'm a still learning how to program in school. I'm having an issue reading in to a dynamically created array with a pointer to one of my classes. The function readClassArray() isn't getting the variable back from student.getCreditNumber. The program complies fine in Visual Studio but when I get the the readClassArray it just skips over the function because s.getCreditNumber returns 0.
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
using namespace std;
class Courses{
private:
int courseNumber;
double hours;
string courseName;
char grade;
public:
void setCourseNumber(int n){courseNumber = n; }
void setCreditHours(double c) { hours = c; }
void setCourseName(string n) { courseName = n; }
void setGrade(char g) { grade = g; }
int getCourseNumber() { return courseNumber; }
double getCreditHours() { return hours; }
string getCourseName() { return courseName; }
char getGrade() { return grade; }
};
class Student : public Courses{
private:
string firstName;
string lastName;
string studentNumber;
int creditNumber;
double gpa;
public:
Courses * courses;
Student() {
firstName = " ";
lastName = " ";
studentNumber = " ";
creditNumber = 0;
gpa = 0.0;
courses = NULL;
}
~Student() {
delete[] courses;
};
void setFirstName(string n) { firstName = n; }
void setLastName(string l) { lastName = l; }
void setStudentNumber(string a) { studentNumber = a; }
void setCreditNumber(int num) { creditNumber = num; }
string getFirstName() { return firstName; }
string getLastName() { return lastName; }
string getStudentNumber() { return studentNumber; }
int getCreditNumber() { return creditNumber; }
};
#endif
Student.cpp
#include "Student.h"
#include <iostream>
#include <string>
using namespace std;
void readStudent();
void readCourseArray();
void computeGPA();
void printSummary();
void readStudent() {
Student a;
string number;
string firstName;
string lastName;
int courses;
cout << "Enter student number: ";
cin >> number;
a.setStudentNumber(number);
cout << "Enter student first name: ";
cin >> firstName;
a.setFirstName(firstName);
cout << "Enter student last name: ";
cin >> lastName;
a.setLastName(lastName);
cout << "Enter student number of courses: ";
cin >> courses;
a.setCreditNumber(courses);
cout << "\n"; }
void readCourseArray(){
Student s;
s.courses = new Courses[s.getCreditNumber()];
int num;
double cHours;
string cName;
char grade;
cout << "test" << endl;
for (int i = 0; i < s.getCreditNumber(); i++){
cout << "Enter class " << i + 1 << " number: ";
cin >> num;
s.courses[i].setCourseNumber(num);
cout << "Enter class " << i + 1 << " name: ";
cin >> cName;
s.courses[i].setCourseName(cName);
cout << "Enter class " << i + 1 << " hours: ";
cin >> cHours;
s.courses[i].setCreditHours(cHours);
cout << "Enter class " << i + 1 << " grade: ";
cin >> grade;
s.courses[i].setGrade(grade);
cout << "\n";
}
}
At the start of readCourseArray you've created s. When that happens the value of the creditNumber member is 0 as set by the default constructor. You need to do something to set it to a non-zero value. If you're expecting the value set in readStudent to carry over you need to plumb the two functions together. Either pass in a Student object as a reference to each function, or have readStudent return a Student object and pass that to readCourseArray.
I'm not really sure if the title is correct but i have the following piece of code:
#include <iostream>
#include <string>
using namespace std;
class department
{
private:
string name;
int budget;
public:
int NoT; //Number of teachers
int NoS; //Number of students
void setName(string nam);
void setBudget(int budg);
int getBudget ();
string getName();
};
class school
{
private:
int YoE;
string name;
public:
department *dpt;
int NoDpts;
school();
};
void department::setName(string nam)
{
name=nam;
}
void department::setBudget(int budg)
{
budget=budg;
}
int department::getBudget()
{
return budget;
}
string department::getName()
{
return name;
}
school::school()
{
YoE=2000; // Year of estabilishment
name="Somename";
NoDpts=37;
}
int main()
{
string name;
int budget;
int budg;
school *sch;
sch=new school;
if (!sch)
throw("Out of memory");
sch->dpt=new department[37];
if (!sch->dpt)
throw("Out of memory");
for (int i=0;i<sch->NoDpts;i++)
{
cout << "Insert name for department#" << i+1 << ": ";
cin >> name;
sch->dpt->setName(name);
cout << "Insert budget for department " << name << ": ";
cin >> budget;
sch->dpt->setBudget(budget);
cin.ignore();
}
cout << "Insert a budget for school: ";
cin >> budget;
for (int i=0;i<sch->NoDpts;i++)
{
if (budg=sch->dpt->getBudget()>=budget)
{
cout << "Name of department is: " << sch->dpt->getName() << endl;
cout << "Budget of department amounts to: " << sch->dpt->getBudget() << endl;
cout << endl;
}
}
return 0;
}
As you can see, i allocated 37 departments, however i don't know how to access them.I mean that in the following line:
sch->dpt->setName(name);
I merely access the name of the first department (indirectly by using an accessor function),thus overwriting it and getting different results than expected.This happens to other members too such as
sch->dpt->setBudget(budget);
So i am simply asking how i can access the members of the rest of the departments.
I have recently tried to learn how to create an object of vectors in order to represent objects of students including their names and grades. but when I wrote my program I got some errors regarding using &. I do not know what is the problem with my errors. could you please help me to fix it?
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void printvector(const vector< student>&); // fill vector.fill in student information
void fillvector(vector< student>&); // print the information of all students
class student {
public:
student();
student(string, char);
~student();
string getName() ;
char getGrade() ;
void setName(string);
void setGrade(char);
private:
string newName;
char newGrade;
};
student::student() { newGrade = ' '; }
student::student(string name, char grade) {
newName = name;
newGrade = grade;
}
student::~student(){ }
string student::getName() { return newName; }
char student::getGrade() { return newGrade; }
void student::setName(string name) { newName = name; }
void student::setGrade(char grade) { newGrade = grade; }
int main() {
vector<student> myclass;
printvector(myclass);
fillvector(myclass);
return 0;
}
void fillvector(vector< student>& newmyclass) {
string name;
char grade;
int classsize;
cout << "how many students are in your class?";
cin >> classsize;
for (int i = 0; i < classsize; i++) {
cout << "enter student name";
cin >> name;
cout << "enter student grade";
cin >> grade;
student newstudent(name, grade);
newmyclass.push_back(newstudent);
cout << endl;
}
}
void printvector( vector< student>& newmyclass) {
unsigned int size = newmyclass.size();
for (unsigned int i = 0; i < size; i++) {
cout << "student name:" << newmyclass[i].getName() << endl;
cout << endl;
cout << "student grade" << newmyclass[i].getGrade() << endl;
cout << endl;
}
}
It seems you're printing your vector before filling it.. Is your problem fixed when you swap them around?
int main() {
vector<student> myclass;
printvector(myclass); // <--- These two lines should probably be swapped
fillvector(myclass); // <---
return 0;
}
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.