Can I do something like this in C++:
Code:string line; char sentence[]; cout << "Please enter a string: "; cin >> line; sentence = line;
Can I do something like this in C++:
Code:string line; char sentence[]; cout << "Please enter a string: "; cin >> line; sentence = line;
The last part is not correct but you can have something likeCan I do something like this in C++
Code:string line; char *sentence; cout << "Please enter a string: "; cin >> line; sentence = line.c_str();
@Aslaville
Your sentence pointer should be const in your example since that's what c_str() returns (and you're not allowed to modify the data through that pointer). Maybe the OP wants a copy:
Remember to delete [] sentence at some point.Code:char *sentence = new char[line.size() + 1]; std::strcpy(sentence, line.c_str()); // include <cstring> header
Last edited by algorism; 04-15-2016 at 03:42 PM.
I was doing that and get the following:
cannot convert from 'const char *' to 'char *'
If you really want a C-string copy of a string for some reason, I prefer this:
Run the code, see for yourself.Code:#include <string> #include <iostream> using namespace std; int main() { string line = "Some string from somewhere\n"; char *sentence = new char [line.length() + 1]; size_t sentence_length = line.copy(sentence, line.length() - 1); sentence[sentence_length] = '\0'; cout << "The sentence is " << sentence_length << " characters long.\n"; cout << "sentence=\"" << sentence << "\"\n"; cout << "Make whatever copies you want! Here\'s a substring!\n"; sentence_length = line.copy(sentence, 6, 5); sentence[sentence_length] = '\0'; cout << "The sentence is " << sentence_length << " characters long.\n"; cout << "sentence=\"" << sentence << "\"\n"; delete[] sentence; sentence = 0; }
Why is no one in this thread using smart pointers?!?!?!
OP, for reference, a smart pointer is simply a type where you construct it with a pointer and when the smart pointer goes out of scope, the memory is automatically freed.
Basically, it's like:
Code:std::unique_ptr<char[]> sentence{new char[length_of_string]};
Them having nothing to do with the question might be a reason.Why is no one in this thread using smart pointers?!?!?!
They became relevant once algorism introduced new[] and mentioned delete[].Originally Posted by whiteflags
Anyway, no point using new[] and delete[] here, with or without a smart pointer. Aslaville's suggestion would be applicable if the null terminated string will not be modified, but since it apparently will be, it would suffice to null terminate a std::string:
Code:cout << "Please enter a string: "; string line; cin >> line; line.push_back('\0'); char* sentence = &line[0];
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)