- #1
yungman
- 5,738
- 290
Question
Is there anyway to copy the content of a string into a C-String and make the length of C-String the right length of the string? This is the program I try to do, of cause this is NOT working. I don't know of any way to do this. I just want to run by you experts whether it's possible that I have not learn in the book. This is what I want to do, I want to input a name into ST1, I use a string pointer ptr to allocate memory of length of St1. Then store the content of St1 into the allocated memory and then finally print the content of the memory.
Book never teach this, I just wonder whether I can do it or not. Point is I want to allocate just enough memory for the length of the string from the getline(cin, St1).
Thanks
Is there anyway to copy the content of a string into a C-String and make the length of C-String the right length of the string? This is the program I try to do, of cause this is NOT working. I don't know of any way to do this. I just want to run by you experts whether it's possible that I have not learn in the book. This is what I want to do, I want to input a name into ST1, I use a string pointer ptr to allocate memory of length of St1. Then store the content of St1 into the allocated memory and then finally print the content of the memory.
C++:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
string St1;
cout << " Enter a name: "; getline(cin, St1);
int length = St1.length();
string* ptr;
ptr = new string[length];
*ptr = St1;
cout << " The name stored in memory is: " << *ptr << "\n\n";
delete[] ptr;
return 0;
}
Book never teach this, I just wonder whether I can do it or not. Point is I want to allocate just enough memory for the length of the string from the getline(cin, St1).
Thanks