std::stringstr;
chararray[]="Hello World";
for(inti=0; array[i]!=0; i++)
str+=array[i];
//-----------------------------------
std::stringstr;
chararray[]="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>
usingnamespacestd;
intmain()
{
inti;
charstr[]="Hello \0World";
strings=str;
cout<<s<<endl;<<output="Hello"
intsz=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"
return0;
}
intmain()
{
inti;
strings;
charstr[]="Hello \0World";
intsz=sizeof(str);
s.assign(str,sz);
sz=s.length();
for(i=0; i<sz; i++)
cout<<s[i];
cout<<endl;
return0;
}
原文链接: https://www.cnblogs.com/smartvessel/archive/2011/05/12/2044040.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/25362
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!