Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 580
fbrereto Avatar asked Jun 16 '10 23:06

fbrereto


People also ask

How do I go to a previous line in C++?

There is no portable way to go back one line in C++. You can go to the beginning of the line by printing \r , but moving to the previous line requires platform dependent code. If don't want to use libraries like Curses, you can try ANSI escape codes.

How do I do a cout return?

cout does not have a return value. cout is an object of type ostream . operator << has a return value, it returns a reference to cout .

How do you stop cout without a new line?

The cout operator does not insert a line break at the end of the output. One way to print two lines is to use the endl manipulator, which will put in a line break. The new line character \n can be used as an alternative to endl. The backslash (\) is called an escape character and indicates a special character.


2 Answers

"\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 
like image 114
Logan Capaldo Avatar answered Sep 17 '22 17:09

Logan Capaldo


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).

like image 36
Nathan Ernst Avatar answered Sep 16 '22 17:09

Nathan Ernst