为什么这个c ++字符串连接缺少空格?

Dan*_*Dan 1 c++ string io

我正在使用c ++字符串,并且是编程的初学者.

我期待:99个红色气球

但我收到了:99 RedBalloons

这是为什么?

#include <string>
#include <iostream>
using namespace std;

int main()
{
    string text = "9";
    string term( "9 ");
    string info = "Toys";
    string color;
    char hue[4] = {'R','e','d','\0'};
    color = hue;
    info = "Balloons";
    text += (term + color + info);
    cout << endl << text << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Soa*_*Box 11

您的定义hue不包括任何空格.(\ 0是C++如何知道字符串结尾的位置,这不是空格.)请注意,term在您的代码中确实有一个尾随空格.

要解决此问题,请将hue更改为:

char hue[5] = {'R','e','d',' ','\0'};
Run Code Online (Sandbox Code Playgroud)

或者,在构造最终文本时,在添加中包含一个空格:

text += (term + color + " " + info);
Run Code Online (Sandbox Code Playgroud)