New to C++

Hi, I am new to C++ so forgive me if I am doing some things ridiculously stupid.

I want to create a class with private variables with setters and accesors etc, something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class student {
private:
	string name;

public:
	student() {}  //constructor

	//mutator
	void setFirstName(string x) {
		firstname = x;
	}

        //accessor
	string getFirstName() {
		return firstname;
	}
};


Now in the main method say I want to create a student object and input a string for name:
1
2
3
	student p;
	cout << "Enter your first name: ";
        p.setFirstName( ... ) //What goes here? 


Thanks...
1
2
3
string firstname;
getline(cin, firstname);
p.setFirstName(firstname);


Your class's private member is called name, by the way, but both of your accessors return a variable called firstname.

You could also try taking the first name through the constructor.

1
2
3
4
5
6
7
8
9
10
11
12
13
// constructor
student(const string &n) : name(n)
{}

// or...

student(const string &n)
{
    name = n;
}

// inside main...
student p("Name");
Last edited on
Now in the main method say I want to create a student object and input a string for name:
1
2
3
	student p;
	cout << "Enter your first name: ";
        p.setFirstName( ... ) //What goes here? 


In line three would be the string that you want to change the name to.

So if you wanted to get input from the user:
1
2
3
4
5
        string name;
        cout << "Enter your first name: ";
        cin >> name;

        p.setFirstName(name);

OR:
1
2
3
        string name;
        cout << "Enter your first name:";
        p.setFirstName(cin.getline());


This is all covered here: http://cplusplus.com/doc/tutorial/basic_io/
 
p.setFirstName(cin.getline());



That wouldn't work. istream::getline returns the istream you provide (in this case, cin). When you are reading a string from the console use the function I used above.
That wouldn't work. istream::getline returns the istream you provide (in this case, cin). When you are reading a string from the console use the function I used above.


Oops. :)

I actually didn't notice you posted this:
1
2
3
string firstname;
getline(cin, firstname);
p.setFirstName(firstname);


I didn't realize I was repeating you. I guess I ought to read better.
Topic archived. No new replies allowed.