Std :: string stops at \ 0

I'm having problems with std::string..

The problem is that it is '\0'recognized as the end of a line, as in C-like lines.

For example, the 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? Shouldn't it be std::stringtreated '\0'like any other character?

+4
source share
7 answers

Think about it: if you are given const char*, how will you divide, where the true completion is 0, and where is it implemented?

You need to either explicitly pass the size of the string, or build a string of 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

: @Rakete1111 :

using namespace std::literals::string_literals;
auto str = "String!\0 This is a string too!"s;
+7

std::string 7 '\0', . std::basic_string: , . , , :

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

"String!\0 This is a string too!" char const[] char. . , , '\0'. .


, , std::vector<char> std::vector<unsigned char> .

+2

\0

std::string s ("String!\\0 This is a string too!");

, :

31
String!\0 This is a string too!
+1

\0 , - .

String represntation

.

, , "\\0"

'\\0'

   std::string test = "Test\\0 Test"

:

   Test\0 Test

, . :

 std::ifstream some_file("\new_dir\test.txt"); //Wrong
 //You should be using it like this : 
 std::ifstream some_file("\\new_dir\\test.txt"); //Correct
+1

std::string . '\0'. "f\0o", , :

{'f', '\0', 'o', '\0'}

string, char const*, - :

string(char const* s) {
    auto e = s;
    while (*e != '\0') ++e;

    m_length = e - s;
    m_data = new char[m_length + 1];
    memcpy(m_data, s, m_length + 1);
}

, , . '\0', , .

'\0', std::string:

#include <iostream>
#include <string>

int main ()
{
    using namespace std::string_literals;

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

    return 0;
}

:

30
String! This is a string too!
0

++ C.

C . , C \0, . - , "String!\0 This is a string too!"

And not in the second, which is forced and automatically provided by the compiler at the end of your standard C line.

0
source

It is not a problem that the intended behavior.

Perhaps you could explain why you have \ 0 in your line.

Using std :: vector will allow you to use \ 0 in your string.

-1
source

Source: https://habr.com/ru/post/1672629/


All Articles