2010-05-31 60 views
1

我正在使用C++字符串,並且是編程初學者。爲什麼這個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; 
} 

回答

11

您對hue的定義中不包含任何空格。 (\ 0是C++如何知道字符串末尾的位置,這不是空格。)請注意,代碼中的term確實有尾隨空格。

要修復它,改變色調:

char hue[5] = {'R','e','d',' ','\0'}; 

或者,在您的另外一個空間,當你構建最終文本:

text += (term + color + " " + info); 
2

這是因爲該字符串只是串聯字符按字符排列,並且info =「Balloons」或顏色中沒有空格。請注意'\ 0'不是空格。 爲了得到你需要一個空間:

text += (term + color + " " + info); 
2

因爲無論是在COLR年底或信息的開頭是沒有空間。所以你可以試試:

info = " Balloons"; 
相關問題