Harshit Gangwar
Harshit Gangwar

Reputation: 43

string concatenation of character and string

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

Upvotes: 3

Views: 102

Answers (1)

R Sahu
R Sahu

Reputation: 206557

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

Upvotes: 8

Related Questions