i'm new to c++ and have a lack of understanding why this code works well:
string GetString(string promt)
{
cout << promt << ": ";
string temp;
getline(cin, temp);
return temp;
}
int main()
{
string firstName = GetString("Enter your first name");
string lastName = GetString("Enter your last name");
cout<< "Your Name is: " << firstName << " " << lastName;
cin.ignore();
cin.get();
return 0;
}
String-Literals like "bla" are of Type const char*. At least auto i = "bla"; indicates, that i is of Type "const char*". Why is it possible to pass it to the GetString-Function, because the function expects a string and not a const char*?
You absolutely can assign const char* to std::string , it will get copied though. The other way around requires a call to std::string::c_str() .
In C++, string literals are stored in arrays of const char , so that any attempt to modify the literal's contents will trigger a diagnostic at compile time.
In general, you can pass a char * into something that expects a const char * without an explicit cast because that's a safe thing to do (give something modifiable to something that doesn't intend to modify it), but you can't pass a const char * into something expecting a char * (without an explicit cast) because that's ...
1 Answer. Show activity on this post. string is an object meant to hold textual data (a string), and char* is a pointer to a block of memory that is meant to hold textual data (a string). A string "knows" its length, but a char* is just a pointer (to an array of characters) -- it has no length information.
std::string
has a converting constructor which takes a char const*
and initialised the string with the null terminated string pointed to by the pointer. This constructor is not explicit
, so it can be used in implicit conversions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With