代码如下图所示,在main函数中,有两个string类型的变量,其中一个变量str1我直接初始化,另一个变量str2我没有初始化,但是string类型调用默认构造函数,使得str2 = "\0",是这样吧。我对str1的首字符进行了变换,然后用cout可以在后面输出,为什么我对str2的首字符进行变换后,再用cout输出,但是没有得到正确的输出啊。请问这是怎么回事啊?谢谢。
#include <iostream>
#include <string>
int main()
{
std::string str1 = "test";
std::string str2;
if (str2[0] == '\0')
std::cout << "yes" << std::endl;
str1[0] = 'a';
str2[0] = 'b';
std::cout << str1 << '\n'
<< str2 << '\n';
str2[1] ='\0';
std::cout << str1 << '\n'
<< str2 << '\n';
return 0;
}
运行结果:
According to your question.
You created str1, which points to five bytes.
And str2 is empty.
So
you use str1[0]str1[1 ]str1[2]str1[3]str1[4] is fine
But there will be a problem if you use str2[0]. It actually does not point to any memory.
Personal suggestion.
You use C++, it is not recommended to use array subscripts in C language to access.
It would be better to use some functions that come with string to access.
When you output, try outputting str2.data() instead.
str2[0] = 'b'; Should this operation be effective? This question is worth thinking about
because currently str2 is an empty string, that is, empty()==true;
then its size() should be 0, and str2[0] is for the first element access.
This is actually related to the implementation of std::string. You can try it. Some compilers’ built-in implementations will cause errors during this operation.