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.

scohe001
  • 15,110
  • 2
  • 31
  • 51

1 Answers1

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);
R Sahu
  • 204,454
  • 14
  • 159
  • 270