Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string stops at \0

Tags:

c++

string

I am having problems with std::string..

Problem is that '\0' is being recognized as end of the string as in C-like strings.

For example following code:

#include <iostream>
#include <string>

int main ()
{
    std::string s ("String!\0 This is a string too!");
    std::cout << s.length(); // same result as with s.size()
    std::cout << std::endl << s;

    return 0;
}

outputs this:

7
String!

What is the problem here? Shouldn't std::string treat '\0' just as any other character?

like image 900
galaxyworks Avatar asked Mar 18 '17 12:03

galaxyworks


People also ask

Does string have \0 at the end?

String is a data type that stores the sequence of characters in an array. A string in C always ends with a null character (\0), which indicates the termination of the string. Pointer to string in C can be used to point to the starting address of the array, the first character in the array.

What is \0 in a string?

It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message.

What does std::string end () return?

Returns an iterator to the character following the last character of the string.

What does it mean \0 in C++?

The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end. So following will be valid representation of strings in C.


1 Answers

Think about it: if you are given const char*, how will you detemine, where is a true terminating 0, and where is embedded one?

You need to either explicitely pass a size of string, or construct string from two iterators (pointers?)

#include <string>
#include <iostream>


int main()
{
    auto& str = "String!\0 This is a string too!";
    std::string s(std::begin(str), std::end(str));
    std::cout << s.size() << '\n' << s << '\n';
}

Example: http://coliru.stacked-crooked.com/a/d42211b7199d458d

Edit: @Rakete1111 reminded me about string literals:

using namespace std::literals::string_literals;
auto str = "String!\0 This is a string too!"s;
like image 170
Revolver_Ocelot Avatar answered Sep 22 '22 22:09

Revolver_Ocelot