@Spectre said:
@xperroni said:@GuntherVB said:
std::string cut = "blah (" + std::string(cString, 4) + ") blah";
Creates a std::string using four characters from your character array cString. Since cString doesn't contain the required four characters it will copy the first two 0x00's and whatever might be in memory after it, eg. garbage.Actually, no – or at least, it shouldn't. Just as substr() is smart enough to stop at the end of a string that is shorter than the required length, so should string(const char*, size_t) – it can do so quite simply, just checking for the '\0' as it reads the input buffer. But perhaps you're on into something here: the constructor might take that first 0x00 value as an actual character, not the end marker of an empty C-string. Then we end up with an STL string "version" of the end-of-string marker. That would be a bit misleading (because debuggers often show both '\0' and '' characters as the empty string) but not technically incorrect.
Actually yes, it should:
basic_string(const charT* s, size_type n, const Allocator& a = Allocator());Requires: s shall not be a null pointer and n < npos.
Effects: Constructs an object of class <font face="Courier">basic_string</font> and determines its initial string value from the array of <font face="Courier">charT</font> of length n whose first element is designated by s, as indicated in Table 40.
Is that from an online reference? Could you send the link?
@Spectre said:
See? No terminators, predators, or last action heroes are mentioned. RTFS (Read The Friendly Stroustrup).
So it was naive of me to assume that all std::string methods would check for '\0' characters while processing C-string arguments. But I do find it a bit misleading, if not incorrect in itself.
@Spectre said:
@GuntherVB said:
std::cout will try to output the string but it will stop at the first string termination character, eg after the first opening paranthesisAgain, I see no reason for it. Why shouldn't you be able to output NULs?
That was never the point. The point was that, in the first part of the snippet, it seemed the string should go further than what was actually printed. It didn't because IO (as would any code that checks for end markers) ran into a '\0' and correctly stopped right there; the problem was that '\0' should have never gotten into the middle of the string in the first place. My reasoning for why it got there (and whether this behaviour was correct) may have been incomplete, but the second part of the snippet correctly avoids the problem, providing a way to concatenate STL strings and C-strings, even when some of the C-strings have starting '\0' characters.