passing a function in a program has a struct c++ [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 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);

Related

How to use <vector> with constructor

How could I use <vector> for an array of objects, which need to be given value through constructors? e.g class with name,age would need to get in an array with information given through constructor Student(string n, int a ) { name = n , age = a } .
All the data will be given through keyboard..
Here is an example code of a program capable of getting and storing the name and the age of a list of students using vectors. After that, it prints the information stored. I am using MSVC as the compiler, so if you are not on windows, you can remove system("pause"):
#include <vector>
#include <string>
#include <iostream>
using namespace std;
class Student {
public:
Student(string n, int a) : name(n), age(a) {}
string GetName(void) { return name; }
int GetAge(void) { return age; }
private:
string name;
int age;
};
int main(void) {
vector<Student> students;
unsigned int n;
cout << "How many students are there?" << endl;
cin >> n;
for (unsigned int i = 0; i < n; ++i) {
string name;
int age;
cout << endl << "Please give me the information of the student " << i + 1 << endl;
cout << "What is the name of the student?" << endl;
cin >> name;
cout << "What is the age of the student?" << endl;
cin >> age;
students.push_back(Student(name, age));
}
cout << endl << "Printing information of the students" << endl << endl;
for (unsigned int i = 0; i < n; ++i) {
Student& student = students[i];
cout << "Student " << i + 1 << " is " << student.GetName() << " and is " << student.GetAge() << " years old." << endl;
}
system("pause");
return 0;
}
One can use an initializer-list to directly construct a vector of students:
std::vector<Student> students{
{ "John", 22 },
{ "Melissa", 19 }
};
To add a student later one could use member function emplace_back() which just forwards its arguments to the Student constructor:
students.emplace_back( "Andy", 23 );
Pre C++11 one would have to use member function push_back() instead:
students.push_back( Student( "Andy", 23 ) );
More usage examples can be found on the linked reference pages.

Structure of student marks [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 7 years ago.
Improve this question
I have defined a strudent as:
struct student{
char name[50];
int roll;
int marks;
};
And I'm trying to print the student in s who has the highest marks field:
struct student s[5];
int i;
cout << "Enter information of students : " << endl;
for(i=0;i<3;++i)
{
cout <<"Enter roll no : ";
cin>>s[i].roll;
cout << "Enter name : ";
cin >> s[i].name;
cout << endl << "Enter marks : ";
cin >> s[i].marks;
cout << endl;
}
for(int j=0;j<3;j++)
{
if(s[j].marks>60)
{
cout<<s[j].roll<<" "<<s[j].name<<" = "<<s[j].marks<<" is Passed"<<endl;
}
else
{
cout<<s[j].roll<<" "<<s[j].name<<" = "<<s[j].marks<<" is Failed"<< endl;
}
}
cout<<endl;
cout<<endl;
int max=s[0].marks;
for(int k=0; k<3; k++)
{
if(s[k].marks>max)
{
max=s[k].marks;
}
cout<<s[k].roll<<" "<<s[k].name<<" "<<max<<" is top in the class:"<<endl;
}
Right now my prints all the students! I just want the name and roll no of the student who has top marks among all. What am I doing wrong?
You say you: Want the name and roll of the student who has top marks among all the students
To get that you need to find the index of the student with the highest marks. But before I give you an example of how to do that, I'll need the whole s array to be initialized. This means:
Your initialization loop needs to run the size of your array (for(i = 0; i < sizeof(s) / sizeof(s[0]); ++i))
Or your array size needs to match your loop (student s[3])
Once that's done you can effectively use max_element to find your student with the top marks:
const auto it = max_element(cbegin(s), cend(s), [](const auto& lhs, const auto& rhs){ return lhs.marks < rhs.marks; });
it now points to your student with the highest marks, you can print it like this:
cout << it->roll << ' ' << it->name << ' ' << it->marks << " is top in the class\n";
You can see a live example of this here: http://ideone.com/JcPQMI

Calling for function, only returning 0

Alrighty, the goal of what I am trying to do right now is call the function getSingleStudentInfo, which contains the student's number, last name, and age. In the end this program is designed to do two things, the first being the single student info, the second, printing out an array of 20 students. Disregard the second part, as I have not really gotten into that part yet, so ignore anything involving vectors.
The problem that I am having is that in main the first thing that the program will do is ask you to press 1 for the single info or 2 for the full 20 peoples info. The program compiles fine, but what happens is, no matter what number you enter, the program will say "process returned 0 (0x0)" and be done, I'm having a hard time figuring out why it is doing that instead of printing out the single students info, being "student's ID number is 400" "student's last name is: Simmons" "student's age is: 20"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
};
Student s;
int selection;
vector<int> studentNumber (20);
vector<string> lastName;
vector<int> age (20);
void getSingleStudentInfo (int studentNumber, string lastName, int age) {
cout << "Student's ID number is: ";
cout << s.studentNumber << endl;
cout << "Student's last name is: ";
cout << s.lastName << endl;
cout << "Student's age is: ";
cout << s.age << endl;
return;
};
int main()
{
cout << "Press '1' to see a single student data entry" << endl;
cout << "Press '2' to see all 20 student records" << endl;
cin >> selection;
if (selection == 1) {
getSingleStudentInfo;
};
/*for (vector<int>::size_type i = 0; i <= 20; i++)
{
cout << "Student's ID number is: " << 400 + i << endl;
}
return 0;*/
}
You need to call the function, e.g.
if (selection == 1)
{
getSingleStudentInfo(7, "Johnson", 20);
}
However, it seems like by the implementation, this should be a method off of the student itself
struct Student {
int studentNumber = 400;
string lastName = "Simmons";
int age = 20;
void getSingleStudentInfo() const;
};
Then you'd call it off a Student instance
Student s{400, "Simmons", 20};
s.getSingleStudentInfo();
Then if you had a vector of Student you could do
std::vector<Student> students; // assume this has been populated
std::for_each(begin(students),
end(students),
[](const Student& s){s.getSingleStudentInfo();});
To print in columns, you could change your function to something like
void Student::getSingleStudentInfo()
{
cout << s.studentNumber << '\t'
<< s.lastName << '\t'
<< s.age << endl;
};

Sorting names between a Student class

edit. I want to thank the two people who helped me in my code. I fixed my coding as of 7:22 PM PST 9/25/2014. Still having trouble with the sorting though.
So I'm trying to teach myself how to use C++ in order to get ahead of my programming class in school. I've already taken Java so I'm relatively familiar with the structure of the coding but not exactly sure what to be typing. This practice problem is:
1)Ask the user how many people he wants to enter into the list.
2)Read 3 strings, then turn that info into a student class and put the student inside a vector.
3)Sort the list by name. (Extra credit would be to sort the list by Student ID)
4)Print the info of each student in the list.
5)Ask user while answer is 'Y', search the list for a name and print the info correlating to the name
While in Java, this seems pretty easy, I'm having an extremely hard time understanding what is going on in C++.
I currently only have 1, 2, 4 and 5 done. This is what I have so far.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <fstream>
#include <iomanip>
using namespace std;
class Student
{
string myName, myStudentID, myClassID;
public:
Student(string name, string studentID, string classID)
{
myName = name;
myStudentID = studentID;
myClassID = classID;
}
string getName() { return myName; }
string getStudentID() { return myStudentID; }
void printInfo() { cout << myName << setw(15) << myStudentID << setw(10) << myClassID << endl; }
};
int main()
{
int num;
std::vector<Student> studentList;
cout << "How many students do you wish to add to the student list ? " << endl;
cin >> num;
cin.ignore();
for (int a = 0; a < num; a++)
{
string inputName, inputStudentID, inputClassID;
//get name
cout << "Please enter the Student name : ";
getline(cin, inputName);
//get student ID
cout << "Please enter the Student ID number : ";
getline(cin, inputStudentID);
//get class ID
cout << "Please enter the Student class ID : ";
getline(cin, inputClassID);
Student thisStudent(inputName, inputStudentID, inputClassID);
studentList.push_back(thisStudent);
cout << endl;
}
//sort(studentList.begin(), studentList.end());
/*
I never figured out how to sort the list by name.
I do not know how to compare the name of studentList[0] and studentList[1]
to put them in alphabetical order.
*/
cout << endl;; // FORMATTING
cout << "The student list has a size of " << studentList.size() << endl;
cout << endl;; // FORMATTING
cout << "Student Name" << setw(15) << "Student ID" << setw(10) << "Class ID" << endl;
for (int a = 0; a < studentList.size(); a++)
{
studentList[a].printInfo();
}
cout << endl;; // FORMATTING
string searchedName;
char answer;
do
{
cout << endl;; // FORMATTING
cout << "Please type the name of the person you want to search for: ";
getline(cin, searchedName);
for (int a = 0; a < studentList.size(); a++)
{
if (searchedName.compare(studentList[a].getName()) == 0)
{
studentList[a].printInfo();
break;
}
else
if (a == (studentList.size() - 1)) //If went to end of the list, tell them name not found.
cout << "There is no " << searchedName << " in the list. \n";
}
cout << "Would you like to search for another person? \n";
cout << "Y for Yes, N for No. \n";
cin >> answer;
cin.ignore();
} while (answer == 'Y' || answer == 'y');
return 0;
}
You could create a static compare function in class Student to use with std::sort
class Student
{
string myName, myStudentID, myClassID;
// ...
static bool compare_name(const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);}
};
// ...
std::sort(studentList.begin(), studentList.end(), Student::compare_name);
or if your compiler supports lambda functions:
std::sort(studentList.begin(), studentList.end(),
[studentList](const Student & lStudent, const Student & rStudent)
{return (lStudent.myName < rStudent.myName);});

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)