C++ Passing a Class Object String [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
(Code is messy and incomplete) I'm unable to pass the strings first_name and last_name from main into my class objects.
I don't think I'm declaring my string correctly in Student::setName and is probably making it difficult to get it output when I call the other function setScores.
Class declaration:
#include <iostream>
#include <string>
using namespace std;
const int NBR_SCORES = 3;
class Student
{
private:
std::string firstName;
std::string lastName;
int scores[NBR_SCORES];
public:
void setName (string first_name, string last_name);
void setScores ();
Main and functions:
`int main() {
Student student;
std::string first_name, last_name;
cout << "Enter student's first-name and last-name: ";
getline (cin, first_name, ' ');
getline (cin, last_name);
student.setName(first_name, last_name);
student.setScores();
cout << "\nGoodbye" << endl;
return 0;
}
void Student::setName (string first_name, string last_name) {
first_name = firstName;
last_name = lastName;
}
void Student::setScores () {
int i;
int scores[NBR_SCORES];
for (i = 0; i < NBR_SCORES; i++) {
cout << "Enter score " << i + 1 << " for " << firstName<< " " << lastName << endl;
cin >> scores[i];
}
}
`

Related

C++ programming project header/implementation files [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 months ago.
The community is reviewing whether to reopen this question as of 2 months ago.
Improve this question
So i am practicing header files and implementation files for c++ and i cannot seem to display the letter grade for this program. Everything else is working as it should and displaying the correct data except for the letter grade. I have been trying to figure it out and i think it may be something so simple that i am missing but i need an extra set of eyes. i would really appreciate the help!
//Main program
#include <iostream>
#include <string>
#include "studentType.h"
using namespace std;
int main()
{
studentType student;
studentType newStudent("Brain", "Johnson", '*', 85, 95, 3.89);
student.print();
cout << "***************" << endl << endl;
newStudent.print();
cout << "***************" << endl << endl;
return 0;
}
Header File:
#include <string>
using namespace std;
class studentType
{
private:
string firstName;
string lastName;
int grade;
int average;
char courseGrade;
int testScore;
int progScore;
double GPA;
public:
studentType(string fn = "", string ln = "", char courseGrade = '*', int tscore = 0, int pscore = 0, double gpa = 0);
string getFirstName() const;
string getLastName() const;
int getGrade();
char getCourseGrade() const;
int getTestScore() const;
int getProgScore() const;
double getGPA() const;
void setFirstName(string fn);
void setLastName(string ln);
void setGrade();
void setCourseGrade(char courseGrade);
void setTestScore(int tscore);
void setProgScore(int pscore);
void setGPA(double gpa);
void print();
};
Implementation file:
#include <iostream>
#include <string>
#include <iomanip>
#include "studentType.h"
using namespace std;
studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa)
{
firstName = fn;
lastName = ln;
courseGrade = courseGrade;
testScore = tscore;
progScore = pscore;
GPA = gpa;
}
string studentType::getFirstName() const
{
return firstName;
}
string studentType::getLastName() const
{
return lastName;
}
int studentType::getGrade()
{
return grade;
}
char studentType::getCourseGrade() const
{
return courseGrade;
}
int studentType::getTestScore() const
{
return testScore;
}
int studentType::getProgScore() const
{
return progScore;
}
double studentType::getGPA() const
{
return GPA;
}
void studentType::setFirstName(string fn)
{
firstName = fn;
}
void studentType::setLastName(string ln)
{
lastName = ln;
}
void studentType::setGrade()
{
int average = (testScore + progScore) / 2;
if(average >= 90){
courseGrade = 'A';
}
else if(average >= 80){
courseGrade = 'B';
}
else if(average >= 70){
courseGrade = 'C';
}
else if(average >= 60){
courseGrade = 'D';
}
else{
courseGrade = 'F';
}
}
void studentType::setCourseGrade(char courseGrade)
{
courseGrade = courseGrade;
}
void studentType::setTestScore(int tscore)
{
testScore = tscore;
}
void studentType::setProgScore(int pscore)
{
progScore = pscore;
}
void studentType::setGPA(double gpa)
{
GPA = gpa;
}
void studentType::print()
{
cout << "Name: " << firstName << " " << lastName << endl;
cout << "Grade: " << courseGrade << endl;
cout << "Test Score: " << testScore << endl;
cout << "Programming Score: " << progScore << endl;
cout << "GPA: " << GPA << endl;
}
I think it has something to do with the constructor like adding my grade() function but to be honest my brain is fried and i just need some help i have been staring at this for way to long...
You are never calling setGrade(). Maybe you should call it in the class's constructor?
Displaying grade has nothing to do with header/implementation files.
grade is not initialized in the constructor, so it will have some garbage value. The grade is getting computed only in setGrade() method hence you need to call this method from the constructor to update the grade member variable.
Update your constructor to the following to get the correct result.
studentType::studentType(string fn, string ln, char courseGrade, int tscore, int pscore, double gpa)
{
firstName = fn;
lastName = ln;
courseGrade = courseGrade;
testScore = tscore;
progScore = pscore;
GPA = gpa;
setGrade(); // compute grade based on scores
}

C++ Class getting input

I wanna ask you quick question. How can get the name, surname, id and age as an input? These are must be taken as input and variables must be private. How should I code about it?
#include <iostream>
using namespace std;
class Employee{
private:
string Name;
string Surname;
int IdNumber;
int age;
public:
Employee(string isim,string soyisim,int idnumarasi,int yas){
Name = isim;
Surname = soyisim;
IdNumber = idnumarasi;
age = yas;
}
void printEmployee(){
cout << Name << endl;
cout << Surname << endl;
cout << IdNumber <<endl;
cout << age << endl;
}
};
int main() {
Employee employee("John","Lares",12,25);
employee.printEmployee();
return 0;
}
Edited version. I used getline but still cant reach the private variables. How can reach the private variables. Is the only way getter setter functions?
#include <iostream>
using namespace std;
class Employee{
private:
string Name;
string Surname;
int IdNumber;
int age;
public:
Employee(){
Name = isim;
Surname = soyisim;
IdNumber = idnumarasi;
age = yas;
}
void printEmployee(){
cout << Name << endl;
cout << Surname << endl;
cout << IdNumber <<endl;
cout << age << endl;
}
};
int main() {
Employee employee();
getline(cin,employee.Name);
getline(cin,employee.Surname);
getline(cin,employee.IdNumber);
getline(cin,employee.age);
employee.printEmployee();
return 0;
}
One simple way is to use the constructor you have defined
int main()
{
string name, surname;
int id, age;
cin >> name >> surname >> id >> age; // read user input
Employee someone(name, surname, id, age); // create employee from user input
...
}
Using a constructor is the normal way to give class member variables their initial values.
Another more complicated way is to overload operator>>

How to delete the book that have been input and how to make the title, language, and name doesn't error if we put space on it? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Can anyone help me to make a new menu to delete all the books that have been entered? And how to make the title, name, and language can be entered with space?
I've searched other questions about it, many of them using getline. But i don't understand how to use it on class like this.
(Sorry my grammar is bad, i'm not very good in English)
This is the source code that i've been made.
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class Book {
int number, year;
string language, name, title;
Book * head, * next;
public:
Book (string & name, string & title, int number, string & language, int year) {
head = NULL;
this -> name = name;
this -> title = title;
this -> language = language;
this -> number = number;
this -> year = year;
};
~ Book (void) {
delete head;
};
void display (void);
void add (void);
void dellete (string&);
};
void Book :: add (void) {
string name, title, language;
int year, number;
cout << endl << "Author:", cin >> name;
cout << "Title:", cin >> title;
cout << "Number of books:", cin >> number;
cout << "Language:", cin >> language;
cout << "Year of publication:", cin >> year;
Book * p = new Book (name, title, number, language, year);
p -> next = head;
head = p;
}
void Book :: display (void) {
Book * p = head;
while (p) {
cout << "----------------------------- \n";
cout << "Author:" << p -> name << endl;
cout << "Title:" << p -> title << endl;
cout << "Number of books:" << p -> number << endl;
cout << "Language:" << p -> language << endl;
cout << "Year of publication:" << p -> year << endl;
cout << endl;
p = p -> next;
}
}
int main (int argc, char const ** argv) {
string blank = "";
Book * B = new Book (blank, blank, false, blank, 0);
int opt;
cout << "\nBOOK STACKS \n";
for (;;) {
cout << "1) Add a book.\n";
cout << "2) Show all books.\n";
cout << "3) Exit. \n\n";
cout << "Options:", cin >> opt;
switch (opt) {
            case 1:
                B -> add ();
break;
case 2:
B -> display ();
break;
case 3:
exit (0);
default:
continue;
}
}
return 0;
}
Please help me to get the code because it's my mid-test task and i'm still a beginner at programming. Thanks.
If you want to enter data per line, here is an example:
class Book
{
int number;
int year;
std::string language
std::string name;
std::string title;
public:
friend std::istream& operator>>(std::istream& input, Book& b);
//...
};
std::istream& operator>>(std::istream& input, Book& b)
{
std::string text_line;
std::getline(input, text_line);
std::istringstream text_stream(text_line);
text_stream >> b.number >> b.year >> b.language >> b.name >> b.title;
return input;
}
If each data item is on a separate line, you could change operator>> as:
std::istream& operator>>(std::istream& input, Book& b)
{
input >> b.number;
input >> b.year;
std::getline(input, b.language);
std::getline(input, b.name);
std::getline(input, b.title);
return input;
}
An example input from a file:
std::vector<Book> library;
Book b;
while (data_file >> b)
{
library.push_back(b);
}

passing a function in a program has a struct c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i'm struggling in solving this problem regardless of its simplicity but i don't know where is the exact error.
this problem is a practice on structures and it requires from the user to input 2 students' names and their ages and returns the name of the older person using struct and a function for returning the name of the student.
#include <iostream>
#include <string>
using namespace std;
struct student{
string name;
int age;
};
student getOlder(student s1, student s2);
int main()
{
student s1, s2, Max;
cout << "Enter the first sudent's name" << endl;
getline(cin, s1.name);
cout << "Enter the first sudent's age" << endl;
cin >> s1.age;
cout << "Enter the second sudent's name" << endl;
getline(cin, s2.name);
cout << "Enter the second sudent's age" << endl;
cin >> s2.age;
Max = getOlder(s1, s2);
cout << Max << " is the older student " << endl;
}
student getOlder(student s1, student s2)
{
if (s1.age > s2.age){
cout << s1.name << endl;
}
cout << s2.name << endl;
return result;
}
You need to return the older student:
student getOlder(student s1, student s2)
{
if (s1.age > s2.age)
{
return s1;
}
return s2;
}
Also, since you are not changing the content of s1 or s2, they should be passed as constant references:
student getOlder(const student& s1, const student& s2)
{
// ...
}
Edit 1: Overloading comparison operators
Optionally, you can add methods for comparison:
struct student
{
std::string name;
unsigned int age; // int implies age can be negative.
bool operator>(const student& s2)
{
return age > s2.age;
}
}
This allows you to write things like:
if (s1 > s2)
{
cout << "Student " << s1.name << " is older than " << s2.name << endl;
}
The problem is that result in your final function was never declared. You can set it equal to s1 or s2 during the if/else:
student result;
if(s1.age>s2.age){
result=s1;
}else{
result=s2;
}
return result
Or you could skip over the result part and just return the student:
if (s1.age > s2.age)
{
return (s1);
}
return(s2);

c++ array of type " class student" [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have this c++ assignment....and iam having a bit of a problem since iam used more to c#
i created a class student in order to create an array with different elements...the problem is how can i see the array in the functions in the class part...inorder to fill it with students details and display it..here is the code:
#include <iostream>
#include <string>
#include <array>
#include <iomanip>
using namespace std;
class student{
private:
int id, age;
string fname, lname, cob;
char s;
int stdcount;
public:
void addstd();
void searchstd(int n);
void displayinfo();
void deletestd(int n);
void displayrange();
void modifyinfo(int n);
};
void student::addstd()
{
cout<<"Enter ID Number"<<endl;
cin>>id;
cout<<"Enter First Name"<<endl;
cin>>fname;
cout<<"Enter last Name"<<endl;
cin>>lname;
cout<<"Enter age"<<endl;
cin>>age;
cout<<"Enter student's Sex(F or M) "<<endl;
cin>>s;
cout<<"Enter Country of birth"<<endl;
cin>>cob;
}
void student::displayinfo()
{
for(int i=0;i<100;i++)
{
cout<<ar[i];
}
}
void student::searchstd(int m)
{
}
void main()
{
student s;
student std[100];
int choice;
do{
cout << "-----------Menu------------" << endl;
cout << " 1. Add a student " << endl;
cout << " 2. Search for student by ID " << endl;
cout << " 3. Display all students information " << endl;
cout << " 4. Remove a students " << endl;
cout << " 5. Display students aged between 34 - 50 " << endl;
cout << " 6. Modify a student's information " << endl;
cout << " 7. Exit " << endl;
cout << " Enter your choice 1, 2, 3, 4 ,5,6,7 " << endl;
cin>>choice;
switch(choice) {
case 1:
for(int i=0;i<3;i++)
{
std[i].addstd();
}
break;
case 2:
int numid;
cout <<"enter id "<<endl;
cin>>numid;
s.searchstd(numid);
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
default:
cout << "Please enter 1, 2, 3, 4, 5, 6 or 7 : " << endl << endl;
}
}while(choice!=7);
}
Your problem has very little to do with C++ and everything to do with proper design. Even if you used C#, you would have very little, if any justification for creating a student object as the way you did for C++.
First, as others have mentioned, a student should only know about themself (first name, last name). It isn't a student's responsibility to keep track of other students. A very rough design would look like this:
#include <string>
class student {
private:
int id, age;
std::string fname, lname, cob;
char s;
public:
student() {}
void setId(int n) { id = n; }
void setFirstName(const std::string& s) { fname = s; }
void setLastName(const std::string& s) { lname = s; }
//etc..
int getId() const { return id; }
std::string getFirstName() const { return fname; }
std::string getLastName() const { return lname; }
// etc...
};
That is all a student should have. Setting and getting the student's information. Nothing more, nothing less. You can embellish this by adding a constructor to easily create an entire student in one call (if you want to do this). But this is the basic gist of what a student class should look like.
Now you create an array of these students:
typedef std::array<student, 100> StudentList; // creates an array of 100 students.
or preferably, a vector< student >, so that it becomes a lot easier to handle:
#include <vector>
//..
typedef std::vector<student> StudentList;
Then you use StudentList as your array / vector of students.
It then becomes trivial when it comes to display the students -- just go through the array one by one and display the students information.
Modify your displayInfo function to take an input
void student::displayInfo(student ar[], int numStudents)
{
for(int i=0;i<numStudents;i++)
{
cout<<ar[i]; // if you have << operator defined
}
}
Then in main you could say:
student std[100];
displayInfo (std, 100); // this is passing your array in (you need to populate it though)