views:

115

answers:

3

I am working with c++ strings, and am a beginner at programming.

I am expecting: 99 Red Balloons

But I am receiving: 99 RedBalloons

Why is that?

#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  A: 

Your definition of hue does not include any spaces. (The \0 is how C++ knows where the end of the string is, this is not a space.) Note that term in your code does have a trailing space.

To fix it, change hue to:

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

Or, include a space in your addition, when you construct the final text:

text += (term + color + " " + info);
SoapBox
+2  A: 

It's because the strings are just concatenated character by character and there is no space in info = "Balloons" or in color. Note that the '\0' is not a space. To get a space you would need:

 text += (term + color + " " + info);
shuttle87
+2  A: 

Because there is no space either at the end of colr or at the begining of info. So you can try:

 info = " Balloons";
Vincent Ramdhanie