converting char array to string type

std::string str;
char array[] = "Hello World";
for(int i = 0; array[i] != 0; i++)
   str 
+= array[i];
//-----------------------------------
std::string str;
char array[] = "Hello World";

str 
= array;
Use of NULL is discouraged in C++ because it can be redefined to be anything one wants -- c++ standards do not dictate what NULL should be.

The '\0' and 0 are one in the same thing. The compiler will translate '\0' to 0 during compilation.

All C-style strings are said to be NULL-terminated -- that definition is carry-over from C language. It really means that the end of the string is indicated by the byte which contains a 0.

you cannot assign C-strings that have enbedded 0s to std::string as I posted earlier. As you found out the assignment stops at the first 0. You could do it one character at a time, but then std::string is no longer an ascii string but a binary string, and most of the std::string methods cannot be used, again because of embedded 0s.

In this example, the output of the first cout is jest "Hello" because of the embedded 0.
#include <string>
#include 
<iostream>
using namespace std;

int main()
{
    
int i;
    
char str[] = "Hello \0World";
    
string s = str;
    cout 
<< s << endl; << output = "Hello"
    
int sz = sizeof(str);
    s 
= "";
    
for(i = 0; i < sz; i++)
        s 
+= str[i];

    cout 
<< s << endl;
 
// now assign characters one at a time
    sz = s.length();
    
for(i = 0; i < sz; i++)
        cout 
<< s[i];
    cout 
<< endl; output = "Hello World" 
    
return 0;

} 

int main()
{
    
int i;
    
string s;
    
char str[] = "Hello \0World";
    
int sz = sizeof(str);
    s.assign(str,sz);
    sz 
= s.length();
    
for(i = 0; i < sz; i++)
        cout 
<< s[i];
    cout 
<< endl;
    
return 0;

} 

原文地址:https://www.cnblogs.com/smartvessel/p/2044040.html