0
#include<iostream>
using namespace std;
int main()
{
    string s = "AA";
    cout << s.length() <<"    "<< s << endl;
    s[1] = '\0';
    s[0] = '\0';
    cout << s.length() <<"    "<< s << endl;
    string w = "\0";
    cout << w.length() <<"    "<< w << endl;
    return 0;
}

output

2    AA
2
0

why the second output is 2 instead of 0?
I tried to find the answer on the Internet but couldn't find it.
Can someone answer me?

thank you

joe brave
  • 13
  • 2

1 Answers1

2

Since C++11 it is guaranteed that a std::string is null-terminated, but adding any \0 char to a string does not change its length.

In C++, a string can contain a \0 char because its length is solely defined by the size stored in the object and not by the occurrence of any \0 char within the string.

You need to resize the string manually if you want a \0 char anywhere in the string to affect its length:

s.resize(strlen(s.c_str()))

But, if you already know where you place the \0 char then you should use s.resize() right from the beginning to resize the string instead of placing a \0 char.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • 1
    @joebrave writing in **bold** should only be used to **highlight** certain parts of the text. Don't use that as a default, neither in the comment nor in the answer nor in the question or answer section. – t.niese Feb 01 '20 at 06:06
  • Thank you for your correction. I am new to this site and my English is not good. I am sorry for using the wrong format. – joe brave Feb 01 '20 at 06:26
  • @joebrave a bad english - as long as it is somehow understandable - is not a problem. But not writing **everything in bold** (or EVERYTHING IN UPPERCASE) is a rule that applies anywhere not only here on StackOverflow. – t.niese Feb 01 '20 at 06:28
  • yeah, i will remember this. – joe brave Feb 01 '20 at 06:33