How can I make the class return the entered string

Its compiling but not returning anything. How do i return the string from the class. Thanks.

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
  #include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

class addressBook
{
	public:
	string Getname() {return itsName;}
	string theSpare = itsName;
	private:
	string itsName;
	string itsStreetNumber;
	string itsTown;
	string itsCounty;
	string itsPostcode;
	
};

int main()
{
	addressBook pageOne;
	cout << "Enter the name.\n";
	getline(cin,pageOne.theSpare);
	cout << "The line entered was " << pageOne.Getname()<< endl;
What this line string theSpare = itsName; says is "assign the current value of itsName to theSpare". It does not make theSpare an alias for itsName. If you want to modify the value of itsName you need to std::getline() into it, on line 26.
Last edited on
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
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

class addressBook
{
public:
	addressBook(); //a default constructor
	string Setname(string name) { name = itsName; }
	string Getname() { return itsName; }

private:
	string itsName;
	string itsStreetNumber;
	string itsTown;
	string itsCounty;
	string itsPostcode;

};

addressBook::addressBook() {
	cout << "Enter the name.\n";
	getline(cin, itsName);
}

int main()
{
	addressBook pageOne;
	
	cout << pageOne.Getname();

	cin.get();
	return 0;
}
Please can you show me how you would alter itsName with cin or getlin(cin) without the defualt constructor?
That would be greatly appreciated. Many thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class addressBook{
public:
    void setItsName(const std::string &s){
        this->itsName = s;
    }
    //...
};

//...

std::string line;
std::getline(std::cin, line);

pageOne.setItsName(line);
Last edited on
Without defining a default constructor, it is still done basically the same way...
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
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>

using namespace std;

class addressBook
{
public:
	
	void Setname();
	string Getname() { return itsName; }

private:
	string itsName;
	string itsStreetNumber;
	string itsTown;
	string itsCounty;
	string itsPostcode;

};

void addressBook::Setname() {
	cout << "Enter the name.\n";
	getline(cin, itsName);
}

int main()
{
	addressBook pageOne;
	
        pageOne.Setname();


	cout << pageOne.Getname();

	cin.get();
	return 0;
}
Last edited on
Topic archived. No new replies allowed.