简体   繁体   English

我可以删除 (cout<<" "<

[英]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 :我是 C++ 的初学者,我的问题是我可以删除cout末尾的endl ,例如:

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 .房间里的大象:从cout删除endl

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.但如果您不拥有该代码,您可以尝试“\\033[F”,如果您的终端支持它,它会将您移到上一行。

Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control.另一种可能性是使用rdbufcout缓冲区重定向到您控制的ostream 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 .您可以 (i) 重定向,(ii) 调用使用新行写入错误cout的函数,以及 (iii) 检查您的ostream并写入原始缓冲区,这次省略endl Switch everything back once you're done.完成后切换回所有内容。

Yes of course you do not need to use std::endl every time you use << .是的,当然您不需要每次使用<<都使用std::endl 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 .这里我们从不使用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.你 cout 也只是在字符串文字的末尾使用\\n ,这也会在缓冲区中放置一个换行符。

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".请注意,我没有在最后一个cout<<放置换行符,因此如果还有输出,它将在“line”中的“e”之后立即开始。

Yes you can remove endl.是的,您可以删除 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/还有很多其他的例子,这里是初学者的一个: 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.在这种情况下你没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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