Jump to content

cout in c++


hisoka

Recommended Posts

cout in c++ can be used like this :

 

 

int main(){cout << "green" << "land" << endl;system("pause"); }

 

or like this

 

 

int main(){cout << "green" ;

cout << "land"<<endl ;system("pause"); }

 

output :

 

greenland

 

However I want the output to be

 

green land

 

but I cannot figure out How . I want a space between the two word using cout So how?

 

any idea ?

Link to comment
Share on other sites

Thanks for both of you it works

 

 

I tried another thing :

 

 

this works too

 

int main(){string m = "green";string n = "land";cout<< m + " " + n <<endl;system("pause"); }

 

Now I tried it like that :

 

int main(){cout<< "green" + " " + "land" <<endl;system("pause"); }

 

but it gives an error .

 

8 C:da.cpp invalid operands of types `const char[6]' and `const char[2]' to binary `operator+'

 

I could not understand the error : Any explanation ? and how to correct the little piece code ?

Link to comment
Share on other sites

"the + operator only is used to add numbers. It can't do anything with strings"

 

int main(){string man = "py";string woman = "thon";cout<<man+woman<<endl;system("pause");}

 

output python

 

it concatenates string so it is not only used for math operations but for string concatenation too

 

what do you think?

Link to comment
Share on other sites

These variables:

string m = "green";string n = "land";
are strings. When you do this:
cout<< "green" + " " + "land" <<endl;
those are not strings, they are character array constants, like the error message points out:

8 C:da.cpp invalid operands of types `const char[6]' and `const char[2]' to binary `operator+'

Those are also referred to as C-style strings. C does not have strings, so a string in C is represented as an array of characters terminated by null (which is why the lengths are 6 and 2 instead of 5 and 1, the extra character is a null). You can cast either one as a C++ string and it will work, but like you said there is no point in concatenating 2 literals.
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...