This shows no output:
int x = 10;
cout<<"Hello C++ " + x ;
But this does show output:
int x = 10;
cout<<"Hello C++ ";
cout<<x<<endl;
What is the problem? They seem exactly the same.
BTW I'm Using Visual C++ 6.0 On Visual Studio 2010 .
This shows no output:
int x = 10;
cout<<"Hello C++ " + x ;
But this does show output:
int x = 10;
cout<<"Hello C++ ";
cout<<x<<endl;
What is the problem? They seem exactly the same.
BTW I'm Using Visual C++ 6.0 On Visual Studio 2010 .
Because that's not how to use streams, or strings.
The +
operator is for:
std::string
s together.Here you have a string literal and a number. The +
operator is not compatible with those.
(What you actually end up doing is "adding" 10
to the pointer representing the string literal; as it happens, because your string is ten characters long, that leaves the pointer exactly where your string literal's NULL terminator is, so it is like trying to print ""
.)
The correct approach, as you have yourself found via the second example, is to use the stream's <<
operator again.
cout << "Hello C++ " << x;
How do you append an int to a string in C++?
I suggest you look closely at the above post to tackle your problem.
In C or C++, concatenation is done best using string streams. But to specifically answer your question:
This C++ Code Shows No Output:
int x = 10;
cout<<"Hello C++ " + x ; //uses "+" as you are trying to concatenate an "int" to some output to the stream
But This One which Shows An Output:
int x = 10;
cout<<"Hello C++ "; //output directly to stream
cout<<x<<endl; //same here, no concatenation
What's the problem then, are they exactly the same ? The problem is with "+" concatenation to the stream and NO, they aren't the same! :)
"Hello C++ " + x ;
makes no sense. You add 10 to the address of the string "Hello C++" and then std::cout should do an output of this what is on address "Hello C++" + 10. So this makes simply no sense. std::cout is part of the iostream.
Try using instead of: cout<<"Hello C++ " + x ;
cout<<"Hello C++ " << x ;
int x = 10;
cout << "Hello world!" << ++x;
return 0;
If you want to increment a variable, you should use ++x
. If you want to decrement it, use --x
.
And, if you want to show a variable next to another one, or next to another string, use <<
between them.