0

In C++ strings are copied until a NULL character is received while feeding in a sequence of characters. But if you supply the number of characters to be read, will it copy past the NULL character? I have a situation where I may receive a message that has a NULL character in the middle and still useful information after it. The same question applies to append.

Similarly for find(), will it stop searching if it hits a NULL character?

1
  • 1
    If you are speaking of std::string then yes, they can have \0 in the middle. std::string don't use the "ended by \0" convention. They have memory for storing the size. So they can be used as buffers. Commented Apr 18, 2013 at 15:40

1 Answer 1

3

You should be able to construct a string containing the '\0' character:

const char a[] = "Hello\0world";
std::string s(a, sizeof(a));

std::cout << "a = \"" << a << "\"\n";
std::cout << "s = \"" << s << "\"\n";
std::cout << "sizeof(a)  = " << sizeof(a) << '\n';
std::cout << "strlen(a)  = " << std::strlen(a) << '\n';
std::cout << "s.length() = " << s.length() << '\n';

The above snippet will print

a = "Hello"
s = "Helloworld"
sizeof(a)  = 12
strlen(a)  = 5
s.length() = 12
Sign up to request clarification or add additional context in comments.

5 Comments

Does the output of s also contain the null char or does it just drop the null char?
@legion That is a good question that I don't know the answer to at the moment. Will have to check it.
Interesting results! std::string doesn't know \0 as a string terminator! Poor C-style strings :-D
@legion According to this reference, the output operator for string calls std::basic_streambuf::sputn with the whole string, including the embedded '\0'. My guess is that the '\0' is dropped after the library have written the string to the operating system.
@MM. std::string doesn't care about the C-style terminator, it has its length instead. If you don't provide a length on construction, then of course the string will infer it from finding the C-style terminator character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.