Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;使用char数组创建字符串_C++_Arrays_String_Char - Fatal编程技术网

C++ c++;使用char数组创建字符串

C++ c++;使用char数组创建字符串,c++,arrays,string,char,C++,Arrays,String,Char,目前正在学习字符串,我有以下几种情况: string s; s[0]='a'; s[1]='b'; cout<<s; string s; s.clear(); s+='a'; s+='b'; cout<<s; 字符串s; s[0]='a';s[1]='b'; cout运算符[]返回字符串中位置pos处字符的引用,它读取值,而不是插入和调整std::string的大小 您不能将赋值插入到null中,这就是为什么会出现未定义的行为。首先调整字符串的大小,然后尝试使用操作符

目前正在学习字符串,我有以下几种情况:

string s;
s[0]='a'; s[1]='b';
cout<<s;

string s; s.clear();
s+='a'; s+='b';
cout<<s;
字符串s;
s[0]='a';s[1]='b';

cout运算符
[]
返回字符串中位置
pos
处字符的引用,它读取值,而不是插入和调整
std::string
的大小


您不能将赋值插入到null中,这就是为什么会出现
未定义的行为
。首先调整字符串的大小,然后尝试使用操作符插入。

您需要什么澄清?您发现第一个示例是未定义的行为,所以您是否试图找出原因?在这两种情况下,字符串的大小都为0,但我们只能通过添加而不是赋值来增加该大小。关于这一点,我还有什么需要知道的吗?您只能使用
[]
分配给已经存在的字符串位置,使用
[]
不会增加字符串。您可以这样做
strings;s、 调整大小(2);s[0]='a';s[1]='b';库特