简体   繁体   中英

can I Remove "endl" in ( cout<<" "<<endl ) in C++?

I am beginner at C++, my question is can I remove endl the one at the end of cout like :

cout<<" "<<endl;

I don't want return to new line . If I can't remove it, what should I do?

Elephant in the room: remove the endl from the cout .

But in case you don't own that code, you could try "\\033[F", which, if your terminal supports it, moves you to the previous line.

Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control. You could (i) redirect, (ii) call the function that writes the errant cout with the new line and (iii) inspect your ostream and write to the original buffer, this time omitting the endl . Switch everything back once you're done.

Yes of course you do not need to use std::endl every time you use << . As an example a simple way to print a vector with spaces between the elements would look like:

std::vector<int> foo = {1,2,3,4,5};
for (auto e : foo)
    std::cout << e << " ";

Here we never use a endl . You cout also just use \\n at the end of a string literal and that will put a newline in the buffer as well.

std::cout << "test\n";
std::cout << "this will be on a new line";

Notice that I don't put a newline in the last cout<< so if there is anymore output it will start off right after the "e" in "line".

Yes you can remove endl. It is an optional parameter to the << stream operator of which there are many. If you don't include it then a new Carriage Return/Line Feed character will not be output and therefore text will appear on the same line in the output (presumably console).

For example

cout << "Hello, World" << endl;

would become:

cout << "Hello, World";

or to make the point another way you could write:

cout << "Hello,";
cout << " World";

There are lots of other examples out there too, here's one for starters: http://www.cplusplus.com/doc/tutorial/basic_io/

cout<<"Your message here.";

It's as simple as that. Were you trying to do something like...

cout<<"Your message here."<<; ....? This is wrong as:

The << operator signifies that something comes after the "" part. You don't have any in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM