C++字符串为什么不能用作char数组?

use*_*457 7 c++

int main()
{    
    string a;

    a[0] = '1';
    a[1] = '2';
    a[2] = '\0';

    cout << a;
}
Run Code Online (Sandbox Code Playgroud)

为什么这段代码不起作用?为什么不打印字符串?

Cor*_*lks 7

因为a是空的.如果您尝试使用空数组执行相同的操作,则会遇到相同的问题.你需要给它一些尺寸:

a.resize(5); // Now a is 5 chars long, and you can set them however you want
Run Code Online (Sandbox Code Playgroud)

或者,您可以在实例化时设置大小a:

std::string a(5, ' '); // Now there are 5 spaces, and you can use operator[] to overwrite them
Run Code Online (Sandbox Code Playgroud)


Dav*_*rtz 2

operator[]不支持使用向字符串添加字符。造成这种情况的原因有多种,但其中之一是:

string a;
a[1] = 12;
Run Code Online (Sandbox Code Playgroud)

应该是什么a[0]