3
#include <bits/stdc++.h>
using namespace std;

int main() 
{
    string s1 = "Alice";
    s1 +='\0';
    s1 +='\0';
    cout << s1.size() << endl;         // output: 7

    string s2 = "Alice";
    s2 += "\0";
    s2 += "\0";
    cout << s2.size() << endl;         // output: 5
}

What is wrong here?

Please explain the difference between role of single quotes and double quotes in concatenation.

11
  • 3
    Do you know what a null-terminated string is? Commented Feb 3, 2020 at 20:13
  • 2
    I get a size output of 4 for s2. Commented Feb 3, 2020 at 20:20
  • 1
    @VladfromMoscow Bug - in which implementation of std::string? I can't repro on libstdc++, libc++, and MSVC's library. Commented Feb 3, 2020 at 20:24
  • 1
    Recommended reading: Why should I not #include <bits/stdc++.h>? / Why is “using namespace std;” considered bad practice? Commented Feb 3, 2020 at 20:28
  • 1
    @VladfromMoscow I assume OP just made a typo and that's all. ¯\_(ツ)_/¯ Commented Feb 3, 2020 at 20:29

1 Answer 1

8
s1 +='\0';

adds the character to s1 regardless of what the character is.

s2 += "\0";

adds a null terminated string to s2. Because of that, the embedded null character of the RHS is seen as a string terminator for the purposes of that function. In essence, that is equivalent to

s2 += "";

That explains the difference in output that you observed.

You can use std::string::append to append embedded null characters of a char const* object.

s2.append("\0", 1);
Sign up to request clarification or add additional context in comments.

12 Comments

@R Sahu This explains nothing. There is a bug of the class implementation in the library.
@VladfromMoscow nope, there isn't. It's impossible to know if a null-terminated string has any embedded zeros. After all, the \0 character is the only way to know if the string ended!
@VladfromMoscow, please elaborate.
@VladfromMoscow with "both", you don't mean s2 += "\0"; and s1 +='\0';, do you? '\0' is not a string literal.
@RSahu The question used to say that doing s2 += "\0"; twice increased the string length by one. That was edited out (not by OP), assumed to be a typo. Vlad probably assumes it's not.
|

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.