0

Hi all,

let's say I have a string object. I can cout the string literal by just stating the name of the object or I can use the data function.

string myStringObj = "Hello World!";
cout << myStringObj;
cout << myStringObj.data();

So, why do we have a function like string::data? Surely there must be a good reason!

Thank you,

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by Narue
1

>I can cout the string literal by just stating the
>name of the object or I can use the data function.
Yes to the first part, no to the second. You can "cout the string" by passing just the string object, but it's not safe using the data member function because the data member function doesn't guarantee that the returned string is null terminated. If you change data to c_str, then it's safe.

That's the difference, by the way. c_str returns a null terminated C-style string, data returns a pointer to the first item in an array of characters (which may or may not be null terminated).

Votes + Comments
Thanks a lot.
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.