create class

Hi i am a student. I have an assignment that is to create a class Person which asks the user to input name and age for const 30 max students.

What i have so far is this but i dont know how to make this program run any further. Please help

STUDENT.H
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <string>
#include <iostream>
using namespace std;

//Write a program to read a user's input and store it in the class object below.

class Person
{
	public:
		Person();
		Person(string pname, int page);
		string getName() const;
		void setName(string pname);
		void setAge(int page);
		int getAge() const;
		void print();
	
	private:
		string name;
		int age; //If 0 is unknown.
};


STUDENT.CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "student.h"
#include <iostream>
using namespace std;

Person::Person()
{
	name = "";
	age = 0;
}

Person::Person (string pname, int page)
{
	pname = name;
	page = age;
}

string Person::getName() const
{
	return name;
}

int Person::getAge() const
{
	return age;
}

void Person::print()
{
	cout << "Name : " << name << endl;
	cout << "Age : " << age << endl;
}

/*void Person::SetName() const
{
	cout << "What is the name" << endl;
	cin >> name;
	cout << getName;
}

void Person::setAge()
{
	cout << "What is the age" << endl;
	cin >> age;
	cout << getAge;
}*/


STUDENTMAIN.CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include "student.h"
#include <vector>
using namespace std;


int main()
{
	vector <Person*> Person;
	const int PERSON_SIZE = 30;
	
	
	string age[30];
	int name[30];
	
	for (int i=0; i < PERSON_SIZE; i++);
	{
		Person *pname = new Person(name[i], age[i]);
		people.push_back(age);
	}
	
	/*Person s(pname, page);
	Person s;
	string name;
	int age;
	
	cout << "Enter the name of student." << endl;
	cin >> s;
	
	
	s.Person(name, age);*/
	s.print();
	return 0;
}


I'm having the most trouble creating my main function. help me finish this program. I appreciate any help!
Last edited on
STUDENT.CPP is supposed to have the definition of member functions. Did you post the wrong file?

Line 13 and 14 in STUDENTMAIN.CPP: name is supposed to be string and age should be int. You have them reversed.

Line 19 in STUDENTMAIN.CPP: people.push_back( age ); You haven't defined people.
Last edited on
How do I fix it?
That is what I'm having issue with!


YES, i copied the wrong file. I have updated it now


Could you please give me some tips and tricks on how to get the program running?

Thank you
Last edited on
Found a number of mistakes on multiple files.

1. Try to match the name of the file and the name of the class. If the class name is Person, make it Person.h and Person.cpp instead of STUDENT.H and STUDENT.CPP. Name mismatch will only confuse other people that look at your files.

2. In STUDENT.H, remove parameter from setName and setAge because it seems like you want to ask user to input the data in the setters. Setters usually takes a parameter, but looking at your commented-out setters definition, you are asking user to enter the information in setters instead of main(). Not the way I'd do it, but I will go with your design.

3. In STUDENT.CPP ,you can remove cout << getName; and cout << getAge; in the setters. I can't figure out what you were trying to do there. If you want to print the name and age after the user enter the info, it should be
1
2
cout << getName();
cout<< getAge();

respectively.


Person.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED

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

//Write a program to read a user's input and store it in the class object below.

class Person
{
	public:
		Person();
		Person(string pname, int page);
		string getName() const;
		void setName();
		void setAge();
		int getAge() const;
		void print();

	private:
		string name;
		int age; //If 0 is unknown.
};

#endif // PERSON_H_INCLUDED 



Person.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include "Person.h"
#include <iostream>

using namespace std;

Person::Person()
{
	name = "";
	age = 0;
}

Person::Person (string pname, int page)
{
	pname = name;
	page = age;
}

string Person::getName() const
{
	return name;
}

int Person::getAge() const
{
	return age;
}

void Person::print()
{
	cout << "Name : " << name << endl;
	cout << "Age : " << age << endl;
}

void Person::setName()
{
	cout << "What is the name" << endl;
	cin >> name;
}

void Person::setAge()
{
	cout << "What is the age" << endl;
	cin >> age;
}




main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <vector>
#include "Person.h"

constexpr int MAX_STUDENTS = 30;

int main()
{
    std::vector<Person> people;

    for( int i = 0 ; i < MAX_STUDENTS ; i++ ) {
        Person student{};

        // You have the 's' capitalized in setName() in STUDENT.CPP.
        student.setName();
        student.setAge();

        people.push_back( student );
    }
}


Ok, so this program will ask 30 users to enter their name and age and then it will close out.

Was this what you were trying to do?
Last edited on
mpark4656 you are a life saver.

I am understanding what you're saying. I meant to change the name of the files but never got to it because the program was not running. Thank you for the advice. I'll definitely do that today onwards to make it make more sense.

The inputs also make sense. So thank you for that.

I created a new program to look like what you have written and despite compiling successfully, it does not build.

It's giving me an error saying:
undefined reference to 'Person::Person()'
undefined reference to 'Person::setName()'
undefined reference to 'Person::setAge()'

What do you recommend I do
I included the Person.cpp file in the main.cpp function which made the program run. So that works for now unless you can't do that.

Now when I am entering the data, there is no way for me to quit the program and print the number of students that were entered only.

The program also needs to run again if the age is a negative number or if no value for name is entered.

Explain if possible and also guide me through if you can. I'm having some minor issues doing these basics while using class, constructors, and deconstructors.
Make sure you link all source files.

On linux, I ran the following command and it compiled and built successfully.
g++ -std=c++11 main.cpp Person.cpp


If you are using IDE, try recreating the console project and see if that helps.
Last edited on
I see. I use that command line to link the files.

What it was doing before was just asking for name and then asks for age. And then keeps repeating those steps without printing them.

After I linked the files as you suggested, it asks for the name, then the age. and then in the next two lines it prints them. Which is perfect but not what I was initially trying to do so maybe you could tell me how i can change the code to do that.

Also, I have no way of just pressing Q and printing the names and date enterred.

So what I am trying to fix is:
Enter the names and ages without printing them unless q is enterred. When q is entered it prints out

Person 1:
Name:
Age:

Person 2:
Name:
Age:

etc..

Right now it looks like this.

Enter name: John
Enter age: 21

name: John
age: 21

.
I hope im making sense.

I am also attaching the assignment itself below if it helps you understand my assignment a little better.

I appreciate the help mpark4656. Thank you again

Lab: Person’s class:

Write a program read a user’s input and store the information in a class object below:

class Person

{

public:

Person();

Person (string pname, int page);

string getName() const;

void setName(string pname);

void setAge(int page);

int getAge() const;

private:

string name;

int age; // 0 if unknown

};



You program must have the following:

Your program must include the following:
Implement all the class methods defined above
Must initialize the class object variable with initial value in the default constructor
Name: Noname
Age: 0
Your program will have an user’s menu similar to the one below:
Enter person’s information:
Print out person’s information
Exit
If user selects “1”, the program will ask user to enter person’s name and age. The program must check all user’s input to ensure it is valid input. After the input, your program needs to store the information in an array (maximum 30 person array) and then the program will print out the menu again and waiting for user’s input.
Validate user’s input:
Person’s age must between 0 and 140
Person’s name can’t start with non-alphabet letter (ie: 1st letter of the person’s name must be alphabet letter)
If user selects “2”, the program will print out all the person’s information have entered so far (which is stored in an array). After prints out all the person’s information, the program will print out the menu again and waiting for user’s input.
If user selects “3”, the program will exit.
Your program must include a function that print out your information (similar to lab1 requirement)



Name: print out your name (Your firstname, Lastname)

Class: Class section name (CS-106-02 or CS-106-03)

Date: Today’s date
EDIT: I posted before reading your last post. Will revise and repost code here

Ok, sorry for the delay. I had to go to work.

For right now, I will give you some suggestions after reading the program specification.

Must initialize the class object variable with initial value in the default constructor
Name: Noname
Age: 0


So basically, your default constructor should look like this
1
2
3
4
5
Person::Person()
{
    name = "Noname";
    age = 0;
}




Your program will have an user’s menu similar to the one below:
Enter person’s information:
Print out person’s information
Exit
If user selects “1”, the program will ask user to enter person’s name and age. The program must check all user’s input to ensure it is valid input. After the input, your program needs to store the information in an array (maximum 30 person array) and then the program will print out the menu again and waiting for user’s input.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <cctype>
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"

void promptUserForInput( std::vector<Person> &people )
{
    std::string name;
    int age;

    std::cout << "\nEnter your name: ";
    std::cin >> name;

    while( !isalpha(name[0]) ) {
        std::cout << "Invalid Name!"
                  << "Re-enter your name: ";
        std::cin >> name;
    }

    std::cout << "\nEnter your age: ";
    std::cin >> age;

    while( age > 140 || age < 0 ) {
        std::cout << "Invalid Age!\n"
                  << "Re-enter your age: ";
        std::cin >> age;
    }

    Person person( name , age );
    people.push_back( person );
}

void printInformation( const std::vector<Person> &people )
{
    for( const auto &person : people ) {
        person.print();
    }
}

int main()
{
    std::vector<Person> people;
    int choice = 0;

    while( people.size() < 30 && choice != 3 ) {
        std::cout << "Menu\n\n";
        std::cout << "1. Enter personal information\n"
                  << "2. Print personal information\n"
                  << "3. Exit\n"
                  << "Enter your choice: ";
        std::cin >> choice;

        if( choice == 1 ) {
            promptUserForInput( people );
        }
        else if( choice == 2 ) {
            printInformation( people );
        }
        else if( choice == 3) {
            std::cout << "\nGoodBye";
        }
        else {
            std::cout << "\nInvalid Choice\n";
        }
    }
}


I do not have access to compiler so I couldn't test the code. You may find mistakes in my code, but this is basically what you would have to do to fulfill the requirements.

Anyways, Good Luck and let me know if you need further assistance.
Last edited on
wow I've been stuck at that for so long. It really helps me understand.

The program works like an angel.
But at the beginning of the program I need to ask the user
to either

1. Input name and age for person
2. Print out information that is already stored inside the array
3. End.

I really needed the End function in there that you helped me with. but I need to have it in the beginning as well as through out the program.

To do so should I create the options in the beginning of the main function to output and then use the for loop or switch method?

Or is there something different to be done? If so could you explain it to me?
I will try to work on it then and update you on whether I am able to figure it out on my own or if i need help.

Thanks
Okay! Thanks :)


I have not learnt terms such as
try, catch, auto, and throw yet. Is there a way to use other terms in place of what they do?
Last edited on
You can ignore the code that I posted the first time.

But to answer your question, try, catch, and throw are for error handling, but for this simple exercise, while loop will suffice.

auto is iso11 that allows the compiler to determine variable type based on r-value. You can just explicitly specify the variable type and that's fine.
Hi,
it's okay I had thought something came up. Thanks for getting back to me.

I tried using the code that you sent me but it seems to crash when I input a name.

I read a bit about try, catch, and throw. Is it the same if you were to use cin.clear, cin.clear?


I read a bit about try, catch, and throw. Is it the same if you were to use cin.clear, cin.clear?
No. It's got nothing to do with std::cin -- it's much more general than that. The three keywords are related to exceptions, which allow you to "unwind" the stack in case of an exceptional condition (usually an error) -- to "give up" on an operation and handle it elsewhere.

try...catch lets you handle those exceptional conditions (created with throw)without caring where they come from, only what the program should do next.

They are awfully confusing (at least when abused) in a large program because they can make the flow of control much less predictable. Most importantly, writing exception-safe code that doesn't break things or mess up your data when an exception is thrown is tricky and subtle, so I prefer to avoid exceptions if possible (or handle them ASAP) if I have no choice about it.

They are sometimes appropriate to use when a crash or deadlock (hang) would be inappropriate -- e.g., when you have work that you must do in a destructor somewhere that wouldn't run if the program just died. The process of throwing an exception destroys automatic objects, which can sometimes be really really important.
Last edited on
> I read a bit about try, catch, and throw. Is it the same if you were to use cin.clear, cin.clear?

No, try block is used if you suspect that some code such as function calls will throw an exception. Catch block is used to catch the thrown exception and handle it (Terminate Program, print error and continue, and etc).

For right now, you can simply use while loop to validate the input and not worry about exception. My original code was complicated for no good reason.

If you must learn about exception handling now, try reading these.
https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
http://www.cplusplus.com/doc/tutorial/exceptions/


I'm more interested in where and how your program crashed. Can you post your current code? And also, what name did you use provide as input?


This is the code that I tested online. I've combined them into 1 file because the online compiler that I'm using does not support multi-file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <cctype>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Person
{
	public:
		Person();
		Person(string pname, int page);
		string getName() const;
		void setName( string name );
		void setAge( int age );
		int getAge() const;
		void print() const;

	private:
		string name;
		int age; //If 0 is unknown.
};

Person::Person()
{
	name = "Noname";
	age = 0;
}

Person::Person (string pname, int page)
{
	name = pname;

	age = page;
}

string Person::getName() const
{
	return name;
}

int Person::getAge() const
{
	return age;
}

void Person::print() const
{
	cout << "Name : " << name << endl;
	cout << "Age : " << age << endl;
}

void Person::setName( string name )
{
	this->name = name;
}

void Person::setAge( int age )
{
   this->age = age;
}







void promptUserForInput( std::vector<Person> &people )
{
    std::string name;
    int age;

    std::cout << "\nEnter your name: ";
    std::cin >> name;

    while( !isalpha(name[0]) ) {
        std::cout << "Invalid Name!"
                  << "Re-enter your name: ";
        std::cin >> name;
    }

    std::cout << "\nEnter your age: ";
    std::cin >> age;

    while( age > 140 || age < 0 ) {
        std::cout << "Invalid Age!\n"
                  << "Re-enter your age: ";
        std::cin >> age;
    }

    Person person( name , age );
    people.push_back( person );
}

void printInformation( const std::vector<Person> &people )
{
    for( const auto &person : people ) {
        person.print();
    }
}

int main()
{
    std::vector<Person> people;
    int choice = 0;

    while( people.size() < 30 && choice != 3 ) {
        std::cout << "Menu\n\n";
        std::cout << "1. Enter personal information\n"
                  << "2. Print personal information\n"
                  << "3. Exit\n"
                  << "Enter your choice: ";
        std::cin >> choice;

        if( choice == 1 ) {
            promptUserForInput( people );
        }
        else if( choice == 2 ) {
            printInformation( people );
        }
        else if( choice == 3) {
            std::cout << "\nGoodBye";
        }
        else {
            std::cout << "\nInvalid Choice\n";
        }
    }
}
Last edited on
Here is the code that I have. I didnt do much on it other than what you suggested. I have been reading about the new inputs you have used to get a better understand. But here is all the code put together.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

#include <cctype>
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"

void promptUserForInput( std::vector<Person> &people )
{
    std::string name;
    int age;

    std::cout << "\nEnter your name: ";
    std::cin >> name;

    while( !isalpha(name[0]) ) {
        std::cout << "Invalid Name!"
                  << "Re-enter your name: ";
        std::cin >> name;
    }

    std::cout << "\nEnter your age: ";
    std::cin >> age;

    while( age > 140 || age < 0 ) {
        std::cout << "Invalid Age!\n"
                  << "Re-enter your age: ";
        std::cin >> age;
    }

    Person person( name , age );
    people.push_back( person );
}

void printInformation( const std::vector<Person> &people )
{
    for( const auto &person : people ) {
        person.print();
    }
}

int main()
{
    std::vector<Person> people;
    int choice = 0;

    while( people.size() < 30 && choice != 3 ) {
        std::cout << "Menu\n\n";
        std::cout << "1. Enter personal information\n"
                  << "2. Print personal information\n"
                  << "3. Exit\n"
                  << "Enter your choice: ";
        std::cin >> choice;

        if( choice == 1 ) {
            promptUserForInput( people );
        }
        else if( choice == 2 ) {
            printInformation( people );
        }
        else if( choice == 3) {
            std::cout << "\nGoodBye";
        }
        else {
            std::cout << "\nInvalid Choice\n";
        }
    }
}



Person.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include "Person.h"
#include <iostream>
#include <stdexcept>

using namespace std;

Person::Person()
{
	name = "Noname";
	age = 0;
}

Person::Person (string pname, int page)
{
	name = pname;

	if( page >= 0 && page < 120 ) {
        age = page;
	}
	else {
        throw std::invalid_argument( "Invalid Age" );
	}
}

string Person::getName() const
{
	return name;
}

int Person::getAge() const
{
	return age;
}

void Person::print() const
{
	cout << "Name : " << name << endl;
	cout << "Age : " << age << endl;
}

void Person::setName( string name )
{
	this->name = name;
}

void Person::setAge( int age )
{
    if( age >= 0 && age < 140 ) {
        this->age = age;
    }
    else {
        throw std::invalid_argument( "Invalid Age" );
    }
}


Person.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED

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

//Write a program to read a user's input and store it in the class object below.

class Person
{
	public:
		Person();
		Person(string pname, int page);
		string getName() const;
		void setName( string name );
		void setAge( int age );
		int getAge() const;
		void print() const;

	private:
		string name;
		int age; //If 0 is unknown.
};

#endif // PERSON_H_INCLUDED 


The name is used was Hamza Sheikh.

It's working with a single name but it crashes if a space is entered.
> The name is used was Hamza Sheikh.

That wouldn't work. If you want to include a white space in the name, you may want to use std::getline() instead of std::cin



Try this.

Person.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef PERSON_H_INCLUDED
#define PERSON_H_INCLUDED

#include <string>

class Person
{
	public:
		Person();
		Person( std::string pname , int page );
		std::string getName() const;
		void setName( std::string name );
		void setAge( int age );
		int getAge() const;
		void print() const;

	private:
		std::string name;
		int age;
};

#endif // PERSON_H_INCLUDED 



Person.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "Person.h"
#include <string>
#include <iostream>

Person::Person()
{
	name = "Noname";
	age = 0;
}

Person::Person ( std::string pname, int page)
{
	name = pname;
	age = page;
}

std::string Person::getName() const
{
	return name;
}

int Person::getAge() const
{
	return age;
}

void Person::print() const
{
	std::cout << "Name: " << name << std::endl;
	std::cout << "Age: " << age << std::endl;
        std::cout << std::endl;
}

void Person::setName( std::string name )
{
	this->name = name;
}

void Person::setAge( int age )
{
   this->age = age;
}




main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <cctype>
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"

void promptUserForInput( std::vector<Person> &people )
{
    std::string name;
    int age;

    std::cout << "Enter your name: ";
    std::cin >> std::ws;
    std::getline( std::cin , name );

    while( !isalpha(name[0]) ) {
        std::cout << "Invalid Name!\n"
                  << "Re-enter your name: ";
        std::getline( std::cin , name );
    }

    std::cout << "Enter your age: ";
    std::cin >> age;

    while( age > 140 || age < 0 ) {
        std::cout << "Invalid Age!\n"
                  << "Re-enter your age: ";
        std::cin >> age;
    }

    people.push_back( Person{name , age} );
}

void printInformation( const std::vector<Person> &people )
{
    for( const auto &person : people ) {
        person.print();
    }
}

int main()
{
    std::vector<Person> people;
    int choice = 0;

    while( people.size() < 30 && choice != 3 ) {
        std::cout << "\nMenu\n\n";
        std::cout << "1. Enter personal information\n"
                  << "2. Print personal information\n"
                  << "3. Exit\n\n"
                  << "Enter your choice: ";
        std::cin >> choice;

        if( choice == 1 ) {
            promptUserForInput( people );
        }
        else if( choice == 2 ) {
            std::cout << std::endl;
            printInformation( people );
        }
        else if( choice == 3) {
            ;
        }
        else {
            std::cout << "\nInvalid Choice\n";
        }
    }
}


I believe this code should meet the specifications of the assignment. But it's your job to test the program and make any necessary adjustment.

If you have any questions, feel free to ask.
Last edited on
Thank you for your help!!! I appreciate it a lot
Hey! Could you please take a look at this new code and help me with it. I'm not sure what errors I have made. I would appreciate if you had any time to help.

Thanks

http://www.cplusplus.com/forum/unices/199472/
Topic archived. No new replies allowed.