Initializing a character array

I have a class with a member variable: char * name.

I would like the program to ask for a name, and then create the array based upon the entry. Right now I have this, it works fine:

1
2
3
4
5
6
7
8
void Fun::setName(){
	const int SIZE = 256;
	char temp[SIZE];
	cout << "What is your name? ";
	cin.getline(temp, SIZE, '\n');
	name = new char[cin.gcount() + 1];
	strncpy(name, temp, cin.gcount());	
}


Is there a way to do this without the need for the temp array? Also, I've added 1 to make space for the null terminator, is that necessary

Thanks :)

Edit: is it generally wrong to use a character array? Our teacher explains they are faster than strings, but it seems like the tide is going against them.
Last edited on
Our teacher explains they are faster than strings


I expect they are, especially given that a C++ string is essentially a managed char array with functions attached. The difference is probably on the order of nanoseconds. Given that the user will take billions of times longer than that to type anything in, do you need that time saving? Screwing up char arrays is still one of the most common source of bugs in C and C++ - has been for decades.

Programming is not about making the fastest possible program. It's about making the best trade-off of all possibilities for your particular needs. In this case, just use strings.

1
2
3
4
void Fun::setName(){
	cout << "What is your name? ";
	getline(cin,someMemberString);
}
Last edited on
Topic archived. No new replies allowed.