如何打印一个字符指针,而不是乱搞?

use*_*209 -3 c++ string pointers cout char

所以我试图cout一串字符,我在char指针初始化.问题是,当我开玩笑时,它会打印整个字符串以及一些我不想看到的字符.你怎么解决这个问题?

string text = "A+B";
char *expression;
expression = new char[text.length()];

for(int x=0;x<text.length();x++)
  expression[x] = text[x];

cout << expression << endl;

It displays this:
   A+B²²²²???§s
Run Code Online (Sandbox Code Playgroud)

Rak*_*kib 5

您忘记在字符数组的末尾插入null终止符:

string text = "A+B";
char *expression;
expression = new char[text.length()+1]; //allocate one character more
int x;
for( x=0;x<text.length();x++)
 expression[x] = text[x];
expression[x]=0;  //insert the null terminator
cout << expression << endl;
Run Code Online (Sandbox Code Playgroud)

问题是,在找不到null终止符之前,不认为字符数组已完成.因此它没有停止并且正在打印超出实际阵列.您必须将null终止符标记为数组的结尾.