C++ accepting input in a character pointer using new


Hello,
please i need help. i need to create "Title"(it is a data member of a class) which is a string of variable size and it is dynamically created and defaults to an empty string.
In a class i created a member function setTitle() that prompts the user to enter a title,
its as the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  

Book &setTitle()

	{ 
		char *title="";//the array that is supposed to hold the input
		cout << "Title: ";
		cin >> title;//take the input
		Title = new char[strlen(title)+1];//create a char array for Title of size same as title with an additional for '\0'
		assert(Title != 0);
		strcpy(Title, title);//copying content of title to Title
		cout << Title;
		return *this;
	}

when i run this it give me no error,but when i put a value for Title it stops responding,
please i need help as soon as possible. This should read whole input even with spaces between words
Last edited on
> char *title="";//the array that is supposed to hold the input
¿does it have enough space reserved to hold the input?
also, string literals are constant.
Ofcourse it does. I mean don't pointers to characters have as much space as u input in them.
Doesnt their space expand depending on the input?
What you made is basically a C array, which do not. What you're after is a C++ string. Look at std::string.
Yea but im not supposed to use string. So this little part of the program should function using char arrays and pointers to arrays
georgiod9 wrote:
Ofcourse it does. I mean don't pointers to characters have as much space as u input in them.
Doesnt their space expand depending on the input?
No, everything only has as much space as you allocated, and nothing magically adjusts depending on what you input into it. std::string hides all the dirty work for you by resizing itself as more and more input is available.
So what should i do if i dont want to use string?
Unless your assignment or professor says you have to use C-style strings, always use C++ std::string.
Topic archived. No new replies allowed.