int main() { string a; a[0] = '1'; a[1] = '2'; a[2] = '\0'; cout << a; }
解决方法
因为a是空的.如果您尝试使用空数组执行相同的操作,则会遇到相同的问题.你需要给它一些尺寸:
a.resize(5); // Now a is 5 chars long,and you can set them however you want
或者,您可以在实例化时设置大小:@H_404_5@
std::string a(5,' '); // Now there are 5 spaces,and you can use operator[] to overwrite them