Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are std::string with null-character possible?

Tags:

c++

I initialized a C++ string with a string literal and replaced a char with NULL.

When printed with cout << the full string is printed and the NULL char prints as blank.

When printed as c_str the string print stop at the NULL char as expected.

I'm a little confused. Does the action came from cout? or string?

int main(){
  std::string a("ab0cd");
  a[2] = '\0'; // '\0' is null char

  std::cout << a << std::endl; // abcd
  std::cout << a.c_str() << std::endl; // ab
}

Test it online.

I'm not sure whether the environment is related, anyway, I work with VSCode in Windows 10

like image 621
glaxy Avatar asked Nov 15 '25 21:11

glaxy


1 Answers

First you can narrow down your program to the following:

#include <iostream>
#include <string>

int main(){
    std::string a("ab0cd");
    a[2] = '\0'; // replace '0' with '\0' (same result as NULL, just cleaner)

    std::cout << a << "->" << a.c_str();
}

This prints

abcd->ab

That's because the length of a std::string is known. So it will print all of it's characters and not stop when encountering the null-character. The null-character '\0' (which is equivalent to the value of NULL [both have a value of 0, with different types]), is not printable, so you see only 4 characters. (But this depends on the terminal you use, some might print a placeholder instead)

A const char* represents (usually) a null-terminated string. So when printing a const char* it's length is not known and characters are printed until a null-character is encountered.

like image 155
churill Avatar answered Nov 17 '25 18:11

churill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!