Clear console using C++ with Xcode? - c++

I'm trying to make a C++ console application using Xcode 4.1, but I can't find the command for cleaning the screen while the program is executing...
Any ideas? Thanks!

OSX doesn't have "consoles" the way Windows does. It has pseudoterminals, which act like an old-fashioned glass terminal to the program running "inside" them, and like a bidirectional pipe to the program that set them up. That outer program can do whatever it likes with the inner program's input and output. Notable examples of such programs are Terminal.app, which emulates the venerable VT-100, and ssh, which forwards the I/O over a secure channel to its own controlling terminal (which is probably itself a pseudoterminal). This is all by way of saying that there isn't a method that's guaranteed to work, because maybe the program on the outside of the pseudoterminal doesn't have a "screen" that you can meaningfully "clear." (Expect is a good example of a program like that.)
Having said that, though, if there is a screen, these days you can pretty much count on it to respect the VT-100 control codes. So this should do what you want:
std::cout << "\033[2J" << std::flush;
If you find that you need even one more control code, though, it's time to hook your program up to ncurses, which presents a nice friendly API to all the tricks that modern terminal windows are capable of, and will also have your back in the increasingly unlikely event that your program is attached to a terminal (or a program emulating a terminal) that is not a VT-100 nor one of its descendants.

Related

Invoking a console application from C++ program

I have an console application 'app.exe', which i want to invoke from a C++ program and then communicate with it as if it was a command line. Essentially I want to make a C++ wrapper around another console application so that I could pass input to it at will and receive output.
In pseudo-code something like:
std:string input("...some parameters..."), output;
Process app("app.exe");
app.InputOutput(input, output);
std::cout<<output;
This must have been answered already, but I seem to lack proper terminology to look it up.
In case it matters, I am running Eclipse CDT on Windows 10 with GCC 5.3.0
EDIT: I need to be able to repeatedly send some values to 'app.exe' and repeatedly receive response, rather than just invoke it with parameters. This is needed for a small personal project so I do not care about it being platform-specific.
I used this code as a starting point, in an MFC dialog, to display output from a called process. It was rather painless as this is well documented. He tells you why he is doing what. It should be suitable as you are working with the Windows platform. But as Alf points out, cross platform is something else.
You can use the system function to invoke a shell (command line) command.
That command can be to execute a program with the arguments you want.
system returns the process exit code, but for other results there is no direct support. One easy way to access the output, for a program that just does a job and ends, is to redirect the program's output to a file.
Otherwise you'll have to use communication mechanisms such as pipes or Windows mailslots, that are not supported by the C++ standard library, i.e. you're then into platform-specific code.

NCurses not restoring terminal behavior

Hello dear Communauts,
I'm am creating a terminal animated status report for a parallel software I'm developing. I'm using NCurses.
I'm having an issue related to the restoring of the standard behavior of the terminal.
After running my software the terminal keeps having just 24 lines, no matter if I call endwin() or I don't.
Here the simplified code:
int size=10;
initscr();
refresh();
while(KeepAlive){
int j=1;
mvprintw(j,0,/*Blah blah header*/));
for(int i=0;i<size;i++){
j++;
mvprintw(j,0,/*Some blah blah*/);
}
refresh();
usleep(1000000);
}
endwin();
KeepAlive is a control variable changed by another thread (so the while is not infinite loop, but controlled loop).
After running this software my terminal has only 24 lines, echo works, but there's plenty of blank space.
Thanks a lot for your help, have fun
EDIT:
I would like to share with you some information I found while attempting to solve my issue:
curses (ncurses) is perfectly working under openMP, then you can imagine some threads doing your math calculations and one thread (only one, be aware) giving out some runtime infos.
curse (ncurses) is NOT compatible with MPI. Well, the right stating would be is "not completely" compatible with MPI. MPI is really sophisticated about stdin/stdout/stderr, since all outputs from all MPI-processes could be redirected to a display (which could be specified). Using any advanced terminal output overriding library will take to a fault of the code, or unexpected behaviors.
That's supported by the MPI faq:
Maybe. But probably not.
Open MPI provides fairly sophisticated stdin / stdout / stderr forwarding. >However, it does not work well with curses, ncurses, readline, or other >sophisticated I/O packages that generally require direct control of the terminal.
Every application and I/O library is different -- you should try to see if yours >is supported. But chances are that it won't work.
Sorry. :-(
found here (MPI reference).
What I've discovered is that even if you appoint only one MPI-process to manage all the curses output (just that process calls initscr() at the beginning and endwin() at the end of his part of code) there is no way to force curses to use the full terminal (only default UNIX 24x80 will be available).
Once MPI has been finalized your whole terminal will keep working in 24x80 mode until reset is called.
Thanks to all communauts that helped me,
Have fun
gf
One possible solution is to completely decouple your text GUI from the rest of the MPI code and make both parts talk to each other via the client/server mechanism of MPI-2. That means:
Run the GUI as singleton MPI program, i.e. one that calls MPI_Init{_thread} but is not started via mpiexec. It then should open a listening port by calling MPI_Open_port. The call returns a string port name that has to be supplied to the compute part of the application. The GUI part should then start listening for connections by calling the blocking MPI_Comm_accept.
The compute part is started as usual via mpiexec. It should connect to the GUI by calling MPI_Comm_connect given the port name from (1).
The combination of MPI_Comm_accept in the GUI and MPI_Comm_connect in the compute part establishes an intercommunicator that can be used for sending messages between the two parts. The compute part could e.g. send periodic status messages to the GUI. If necessary, the intercommunicator could be further "flattened" to an intracommunicator.
Once the computation is finished, the communication part should disconnect by calling MPI_Comm_disconnect.
The GUI should call MPI_Close_port and finish its own execution.
In that scenario, the GUI part could be a text mode curses application started locally or remotely via SSH, an X11 GUI application, or whatever else there.
It should work. The comment about "parallel" suggests multithreading, which can mean that your output is not flushed as one might expect.
Likely this is the same issue (Ncurses limited output size) for which more information was given. Neither question provides enough detail to offer more than generic advice.

Prevent mixing of console output and written text

I have a C++ console application that prints some output constantly while it also accepts commands (using std::cin) from the user - output and input happen in separate threads.
If I write a text while some output appears the written text is mixed with application output. How can I prevent this behaviour?
To solve this problem, I need to display the program one line above the line where the text is typed. I'd inspire myself in Minecraft Bukkit server's solution - however I need the same for C++.
Assuming you want the output to appear while things are being typed, you'll need some screen control facilities to have the output go somewhere different than the input area. If I were tasked to implement something like this writing to a terminal I would refresh my ncurses experience. I realize you are on a Windows console and I have no idea if the Windows console is capable of the screen control needed to make it happen.
You can possibly tie custom stream buffers into std::cin and std::cout using the curses functionality under the hood but it may not be worth it. In any case, it isn't entirely trivial.
There's a windows port of ncurses called pdcurses. But if you are using visual studio there's a simple function provided called SetConsoleCursorPosition()

Get trigger from console in C++

I am writing an application for a robot.
The required UI for the application is described in the pseudo-code below:
while(true){
if (spacebar is not pressed){
//do something
}
else{
sleep(1); //wait for a second
}
}
If I use cin or some other console input reading function then it will wait for user to press something. How do I ensure that it does not wait to get any input?
I am using Ubuntu. But I do not want it to be OS-specific.
Answers here seem to be OS specific.
Terminal Level input
What you are asking for is fairly close to the hardware (key-press / key-release) compared to the "standard input/output" stream concepts. So your implementation would have to be OS specific. Having said that the library to use is curses[1] which has been around for a long time and is standard on a lot of Un*x platforms. The GNU ncurses flavor compiles for pretty much all of them, it is a standard install in almost all Linux environments, and where it isn't installed by default you can find it. It also works well in Windows (cygwin), os/2 and a bunch of embedded systems etc. so you should be able to write a fairly portable software using curses that does what you want.
It's not too clear what you're asking for. In the if, is the
condition based on whether a space character has been entered,
or whether the user is currently holding down the space bar? In
the first case, you need something like curses (a portable
library which does gets each character as it was entered,
without echo). In the second, I don't think that there is
a portable solution. Even non-portably, you might not be able
to get it if your program is reading from a terminal window
(e.g. xterm); this sort of information is typically only present
as window events, when you created the window in your program.

Multiple console windows from one Win32 console app

I've written a program based on an empty Win32 console app in VS2008 running on Win7 64bit. The program is entirely menu based spawning from a main.cpp which only calls external functions that lead to other interfaces based on the users needs (e.g. cashier, inventory, report, etc...). What I would love to do is provide a new console window for each interface.
Ideally it would close the main menu upon invoking any other interfaces and so on as the user progresses through its functions, including reopening the main menu when necessary.
The basis for doing it this way is that I'm starting a new semester next week diving deeper in OOP with C++ and I wanted to go over my text and complete the capstone project which progresses with the topics to ensure that I have all the basics down pat. As much as I would love to do this the smartest-easiest way, it's best if I stick to the limited knowledge presented in the book which only hints at STL and speaks nothing of additional libraries like boost.
I, of course, have searched on SO and elsewhere looking for the solution. I have found answers, most of them falling outside of my tight requirements, some dealing with building a console window from scratch. While from-scratch seems the most promising, it seemed to be dealing with those not using a robust IDE like VS and I don't know if it will cause more conflict than it's worth, or if it can even be used in multiplicity. The majority, however, left me with the impression it isn't possible. The one exception to this was linking a console to a process. This is what I hope is in my future!
What brought me to this was the need to present a clean look at each turn of events. At first I was fooling around with trying to clear the screen with a basic function like void clearScreen(int lines); but this will always clear from the bottom. So, if I clear the screen before the next interface it's still at the bottom. If I clear it then accept input, the prompt is still at the bottom.
In case it hasn't been clear up to this point. My question is:
Is it possible, within reason, to produce multiple console windows which are tied to processes, or is there an easy way which I do not know to manipulate the scrolling of the main console window?
Even though I "need" to stay within the confines of the baby-step process of traditional learning, I would love to hear any input aside from switching the app type.
This is more of an OCD issue than a requirement of the task, so if the effort isn't worth the benefit that's okay too.
There is no portable way of moving the cursor around the console window - in Unix/Linux, you can send terminal codes for that, in Windows I have no idea.
What would work cross-platform, but be terribly slow and not too nice, would be:
read your input character-by-character
remember where on the screen the next character should appear
redraw the whole screen after each key press
If you want to do better, you must turn to platform-specific solutions, or find a library which would do it for you (like ncurses in the Unix world), but I don't know if any of these fit in your requirements.
You can set the cursor-position on Windows using SetConsoleCursorPosition.
Since you were saying something about VS, I assume restricting yourself to Windows isn't a problem. If so, you can use the Windows API for this.
Other than that, ncurses seems to be at least partially ported to most common platforms.
If you were looking for a way to do this in standard C++ - it doesn't exist. C++ doesn't require the platform it's running on to even have a console, so there are no console manipulation functions.
Both aren't that hard to use, but if this is really just some student thingy where you expect to learn something useful you probably shouldn't bother. Console manipulation isn't something you'll have or want to do very often.
Although it may not have been clear in my original question, I was looking for a solution to be used in a console window. Ideally the solution would have been operable on at least Linux and Windows because any programs I write for school must be compiled on each. This wasn't an assignment but it's obviously advantageous to learn things that are usable there as well.
Here's what I found ...Solution thanks to Tim Wei
void clearScreen()
{
#ifdef _WIN32
system("cls");
#else
system("clear");
#endif
}
This, as simple as it is, was exactly what I was looking for. The function clears the screen and puts the cursor at the top of the console window providing a way to provide static headers or titles with changing data tables. It also allows for simple text based animations - if you like that sort of thing. It made a significant difference in the look, feel and consistency in my console applications this semester!