我需要打印“ac”作为输出。但是它没有打印任何东西。怎么了
#include<iostream>
#include<string>
using namespace std;
int main()
{
string x;
x[0]='a';
x[1]='c';
x[2]='\0';
cout<<x<<endl;
return 0;
}
最佳答案
该程序具有未定义的行为,因为您可能无法使用下标运算符将值分配给空字符串。
零字符的分配也是多余的。
x[2]='\0';
从C++ 11开始,终止零将自动附加到
std::string
类型的对象。例如,此代码段
string x;
std::cout << static_cast<int>( x[x.size()] ) << '\n';
有效,并且将输出
0
。你可以写
string x;
x += 'a'; // it is the same as x.push_back( 'a' );
x += 'c';
cout<<x<<endl;
或者您可以像这样初始化字符串
string x = { 'a', 'c' };
或使用作业
string x;
x = { 'a', 'c' };
如果要使用下标运算符,则必须使用所需数量的元素创建一个字符串,例如
string x( 2, ' ' );
x[0] = 'a';
x[1] = 'c';
cout<<x<<endl;
关于c++ - 分配后需要打印一个字符串。但是输出为空白。怎么了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58186348/