Rewinding std::cout to go back to the beginning of a line

女生的网名这么多〃 提交于 2019-11-26 10:01:26

问题


I\'m writing a command-line tool for Mac OS X that processes a bunch of files. I would like to show the user the current file being processed, but do not want a bazillion files polluting the terminal window.

Instead I would like to use a single line to output the file path, then reuse that line for the next file. Is there a character (or some other code) to output to std::cout to accomplish this?

Also, if I wanted to re-target this tool for Windows, would the solution be the same for both platforms?


回答1:


"\r" should work for both windows and Mac OS X.

Something like:

std::cout << "will not see this\rwill see this" << std::flush;
std::cout << std::endl; // all done



回答2:


I don't have access to a mac, but from a pure console standpoint, this is going to be largely dependent on how it treats the carriage return and line-feed characters. If you can literally send one or the other to the console, you want to send just a carriage return.

I'm pretty sure Mac treats both carriage returns and line-feeds differently than *nix & windows.

If you're looking for in-place updates (e.g. overwrite the current line), I'd recommend looking at the curses lib. This should provide a platform independent means of doing what you're looking for. (because, even using standard C++, there is no platform independent means of what you're asking for).




回答3:


std::cout interpretes "\r" as return to the beguining of the line, if you dont whant to be adding "<< endl" each time, use "\n"

std::cout << "this will work!\nSee... a new line!" << std::endl;



来源:https://stackoverflow.com/questions/3057977/rewinding-stdcout-to-go-back-to-the-beginning-of-a-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!