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,

>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).

commented: Thanks a lot. +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.