Enter name using Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<cstring>
using namespace std;
class player
{
private: 
char firstname[20];
public:
void setfname (char name[])
{
strcpy (firstname, name);
}
char getFname (void) {return firstname[20];}
};

int main(void)
{
player keith;
char fname[19];
cout<<"what is ur first name";
cin>>fname;
keith.setfname(fname);
cout<<keith.getFname();
}



as you can guess i am trying to code a simple input ur first name and display ur first name program here. However, it display nothing no matter what i enter can anyone please point out my problem?
Last edited on
getFname is returning a single character, not the entire string. And the character it is returning is the 21st character in the array, which contains only 20 characters.
so what am i suppose to return to? i tried firstname[] <-- which gave me an error and i also tried firstname <-- which also gave me an error.
Honestly you should probably just use an std::string, as they're much easier to use and are way safer.

http://www.cplusplus.com/reference/string/string/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <string>

struct foo
{
	std::string bar;
public:
	void setbar(const std::string& str) { bar = str; }
	const std::string& getbar() const { return bar; }
};

int main()
{
	foo a;
	a.setbar("This is a string");
	std::cout << a.getbar() << std::endl;
	return 0;
}
I cna't, becuase i am not fimliar with it and it si required i NEED to use a class and a PUBLIC and PRIVATE and need USER input. )=
Topic archived. No new replies allowed.