在 C++ 中的同一行上打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21870545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing on same line in c++
提问by Zach Starnes
I am trying to write the time on the same line instead of it stacking the outputs. I can not seem to get it to work though.
我试图将时间写在同一行上,而不是将输出堆叠起来。我似乎无法让它工作。
Here is what I have: I thought the "\r"
would make it reprint on the same line, but this doesn't work. And I also tried printf("\r");
and that didn't work either.
这是我所拥有的:我认为"\r"
这会使它在同一行上重印,但这不起作用。而且我也试过了printf("\r");
,也没用。
Can anyone help me figure out how to get this to work?
谁能帮我弄清楚如何让它发挥作用?
void countdown(int time)
{
int h = (time / 3600);
int m = (time / 60) - (h * 60);
int s = time % 60;
std::stringstream ss;
ss << h << ":" << m << ":" << s;
std::string string = ss.str();
cout << "\r" << string << endl;
}
回答by Tony Delroy
cout << "\r" << string << endl;
endl
moves the cursor to the next line. Try replacing it with std::flush
which just ensures output's sent towards the terminal. (You should also #include <iomanip>
and use std::setw(2)
/ std::setfill('0')
to ensure the text you display is constant width, otherwise say the time moves from:
endl
将光标移动到下一行。尝试将其替换为std::flush
确保输出发送到终端。(您还应该#include <iomanip>
使用std::setw(2)
/std::setfill('0')
来确保您显示的文本宽度恒定,否则说时间从:
23:59:59
to
到
0:0:0
The trailing ":59" from the earlier time is not currently being overwritten or cleared (you could write a few spaces or send a clear-to-end-of-line character sequence if your terminal has one, but fixed-width makes more sense).
较早时间的尾随“:59”当前没有被覆盖或清除(如果您的终端有一个空格,您可以写几个空格或发送一个清除到行尾的字符序列,但固定宽度会使更多感觉)。
So ultimately:
所以最终:
std::cout << '\r'
<< std::setw(2) << std::setfill('0') << h << ':'
<< std::setw(2) << m << ':'
<< std::setw(2) << s << std::flush;
回答by michaeltang
endl
inserts a new-line character and flushes the stream.
endl
插入一个换行符并刷新流。
cout << "\r" << string ; //works
回答by songyuanyao
try this:
尝试这个:
cout << "\r" << string;
endl
inserts a new-line character and flushes the stream.
endl
插入一个换行符并刷新流。
回答by Volkan Güven
I want to provide some useful information first.
我想先提供一些有用的信息。
You are inserting std::endl
which prints next string on the next line.
您正在插入std::endl
它在下一行打印下一个字符串。
std::endl
is a newline \n
followed by std::flush
std::endl
是一个换行符,\n
后跟std::flush
The following newline \n
and std::flush
is equivalent to std::endl
.
下面的换行符\n
和std::flush
等价于std::endl
.
std::cout << printFunction() << '\n' << std::flush;
is just like
就像
std::cout << printFunction() << std::endl;
Now removing std::endl
will print the string in the same line.
现在删除std::endl
将在同一行中打印字符串。
cout << "\r" << string;