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

C++ strings why cant be used as char arrays?

本文关键字:字符 数组 不能 字符串 为什么 C++      更新时间:2023-10-16
int main()
{    
    string a;
    a[0] = '1';
    a[1] = '2';
    a[2] = '';
    cout << a;
}

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

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

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

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

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

首先,我认为你的意思是std::string.

其次,您的字符串为空。

第三,虽然您可以使用运算符 [] 来更改字符串中的元素,但不能使用它插入不存在的元素:

std::string a = "12";
a[0] = '3'; //a is now "32"
a[2] = '4'; //doesn't work

为此,您需要首先确保字符串已分配足够的内存。因此,

std::string a = "12";
a[0] = '3'; //a is now "32"
a.resize(3); //a is still "32"
a[2] = '4'; //a is now "324"

第四,你可能想要的是:

#include <string>
#include <iostream>
int main()
{    
    std::string a = "12";    
    std::cout << a;
}

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

string a;
a[1] = 12;

a[0]应该是什么?

在C++中,字符串是一个对象,而不是数组。尝试:

string a = "12";
cout << a;

如果你愿意,你仍然可以使用旧式的C字符串,所以:

char a[3];
a[0] = '1';
a[1] = '2';
a[2] = '';
...

您要做的是混合这两种模式,这就是它不起作用的原因。

编辑:正如其他人指出的那样,只要字符串已以足够的容量初始化,下标std::string对象就可以工作。在这种情况下,字符串为空,因此所有下标都超出界限。

按照 std::string 上的下标运算符的定义:

const char& operator[] ( size_t pos ) const;
      char& operator[] ( size_t pos );

非常量下标是可能的。因此,以下内容应该可以正常工作:

std::string a;
a.resize(2);
a[0] = '1';
a[1] = '2';
std::cout << a;

不过,这似乎是一种迂回的方法。