cin.ignore equivalent in `ncurses` - c++

I have this much cleaner variant to system("Pause") that waits for the user to press enter:
#include <iostream>
void pause()
{
std::cin.get();
std::cin.ignore();
}
However, I couldn't find a clean variant to system("CLS") (or system("clear")), so I switched the whole application to ncurses.
After some reading I found out that ncurses has its own set of I/O functions and that std::cout and std::cin got replaced with echo() and getch().
That function pause() also has to be converted to ncurses, but my problem is that I don't know the correct equivalent to std::cin.ignore.

You can discard input in curses using these functions (not just ncurses):
flushinp
The flushinp routine throws away any typeahead that has been typed by
the user and has not yet been read by the program.
intrflush
If the intrflush option is enabled (bf is TRUE), and an interrupt key
is pressed on the keyboard (interrupt, break, quit), all output in the
tty driver queue will be flushed, giving the effect of faster response
to the interrupt, but causing curses to have the wrong idea of what is
on the screen. Disabling the option (bf is FALSE) prevents the flush.
The default for the option is inherited from the tty driver settings.
The window argument is ignored.

Related

cmd shell flashes across in VS code [duplicate]

Lately, I've been trying to learn C++ from this website. Unfortunately whenever I try to run one of the code samples, I see that program open for about a half second and then immediately close. Is there a way to stop the program from closing immediately so that I can see the fruits of my effort?
If you are using Visual Studio and you are starting the console application out of the IDE:
pressing CTRL-F5 (start without debugging) will start the application and keep the console window open until you press any key.
Edit: As Charles Bailey rightly points out in a comment below, this won't work if there are characters buffered in stdin, and there's really no good way to work around that. If you're running with a debugger attached, John Dibling's suggested solution is probably the cleanest solution to your problem.
That said, I'll leave this here and maybe someone else will find it useful. I've used it a lot as a quick hack of sorts when writing tests during development.
At the end of your main function, you can call std::getchar();
This will get a single character from stdin, thus giving you the "press any key to continue" sort of behavior (if you actually want a "press any key" message, you'll have to print one yourself).
You need to #include <cstdio> for getchar.
The solution by James works for all Platforms.
Alternatively on Windows you can also add the following just before you return from main function:
system("pause");
This will run the pause command which waits till you press a key and also displays a nice message Press any key to continue . . .
If you are using Microsoft's Visual C++ 2010 Express and run into the issue with CTRL+F5 not working for keeping the console open after the program has terminated, take a look at this MSDN thread.
Likely your IDE is set to close the console after a CTRL+F5 run; in fact, an "Empty Project" in Visual C++ 2010 closes the console by default. To change this, do as the Microsoft Moderator suggested:
Please right click your project name and go to Properties page, please expand Configuration Properties -> Linker -> System, please select Console (/SUBSYSTEM:CONSOLE) in SubSystem dropdown. Because, by default, the Empty project does not specify it.
I usually just put a breakpoint on main()'s closing curly brace. When the end of the program is reached by whatever means the breakpoint will hit and you can ALT-Tab to the console window to view the output.
Why not just run the program from a console ie run the program from cmd.exe if you're using Windows. That way the window stays open after the program finishes.
[EDIT]: When I use KDevelop4 there is a fully fledged instance of Bash (a Linux CLI) running in a tab at the bottom of the IDE. Which is what I use in these sort of circumstances.
Before the end of your code, insert this line:
system("pause");
This will keep the console until you hit a key.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
cout << "Please enter your first name followed by a newline\n";
cin >> s;
cout << "Hello, " << s << '\n';
system("pause"); // <----------------------------------
return 0; // This return statement isn't necessary
}
Call cin.get(); 2 times:
//...
cin.get();
cin.get();
return 0
}
If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.
I just do this:
//clear buffer, wait for input to close program
std::cin.clear(); std::cin.ignore(INT_MAX, '\n');
std::cin.get();
return 0;
Note: clearing the cin buffer and such is only necessary if you've used cin at some point earlier in your program. Also using std::numeric_limits::max() is probably better then INT_MAX, but it's a bit wordy and usually unnecessary.
Okay I'm guessing you are on Windows using Visual Studio... why? Well because if you are on some sort of Linux OS then you'd probably be running it from the console.
Anyways, you can add crap to the end of your program like others are suggesting, or you can just hit CTRL + F5 (start without debugging) and Visual Studio will leave the console up once complete.
Another option if you want to run the Debug version and not add crap to your code is to open the console window (Start -> Run -> cmd) and navigate to your Debug output directory. Then, just enter the name of your executable and it will run your debug program in the console. You can then use Visual Studio's attach to process or something if you really want to.
Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.
cin.get();
If you are actually debugging your application in Visual C++, press F5 or the green triangle on the toolbar. If you aren't really debugging it (you have no breakpoints set), press Ctrl+F5 or choose Start Without Debugging on the menus (it's usually on the Debug menu, which I agree is confusing.) It will be a little faster, and more importantly to you, will pause at the end without you having to change your code.
Alternatively, open a command prompt, navigate to the folder where your exe is, and run it by typing its name. That way when it's finished running the command prompt doesn't close and you can see the output. I prefer both of these methods to adding code that stops the app just as its finished.
Add the following lines before any exit() function or before any returns in main():
std::cout << "Paused, press ENTER to continue." << std::endl;
cin.ignore(100000, "\n");
For Visual Studio (and only Visual Studio) the following code snippet gives you a 'wait for keypress to continue' prompt that truly waits for the user to press a new key explicitly, by first flushing the input buffer:
#include <cstdio>
#include <tchar.h>
#include <conio.h>
_tprintf(_T("Press a key to continue "));
while( _kbhit() /* defined in conio.h */ ) _gettch();
_gettch();
Note that this uses the tchar.h macro's to be compatible with multiple 'character sets' (as VC++ calls them).
Use #include "stdafx.h" & system("pause"); just like the code down below.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
std::cout << "hello programmer!\n\nEnter 2 numbers: ";
int x, y;
std::cin >> x >> y;
int w = x*y;
std::cout <<"\nyour answer is: "<< w << endl;
system("pause");
}
simply
#include <cstdio>
int main(){
// code...
std::getchar();
std::getchar();
return 0;
}
for some reason there is usually 1 character possible to read with getchar already in stdin when you run a program. so the first getchar reads this character, and the second getchar waits for user (your) input before exiting the program. And after a program exits most of terminals, especially on Windows close terminal immediately.
so what we aim to is a simple way of preventing a program from finishing after it outputs everything.
Of course there are more complex and clean ways to solve this, but this is the simplest.
Similar idea to yeh answer, just minimalist alternative.
Create a batch file with the following content:
helloworld.exe
pause
Then use the batch file.
See if your IDE has a checkbox in project setting to keep the window open after the program terminates. If not, use std::cin.get(); to read a character at the end of main function. However, be sure to use only line-based input (std::getline) or to deal with leftover unread characters otherwise (std::ignore until newline) because otherwise the .get() at the end will only read the garbage you left unread earlier.
This seems to work well:
cin.clear();
cin.ignore(2);
If you clear the buffer first it won't be a problem when you read the next one.
For some reason cin.ignore(1) does not work, it has to be 2.
You could always just create a batch file. For example, if your program is called helloworld.exe, some code would be:
#echo off
:1
cls
call helloworld.exe
pause >nul
goto :1
If you are running Windows, then you can do system("pause >nul"); or system("pause");. It executes a console command to pause the program until you press a key. >nul prevents it from saying Press any key to continue....
I'm putting a breakpoint at the last return 0 of the program. It works fine.
I used cin.get() and that is worked but one day I needed to use another cin.get([Array Variable]) before that to grab a ling string with blank character in middle of. so the cin.get() didn't avoid command prompt window from closing. Finally I found Another way:
Press CTRL+F5 to open in an external window and Visual Studio does not have control over it anymore. Just will ask you about closing after final commands run.
I tried putting a getchar() function at the end. But it didn't work. So what I did was add two getchar() functions one after another. I think the first getchar() absorbs the Enter key you press after the last data input. So try adding two getchar() functions instead of one
Instead of pressing the run button, press CTRL and F5 at the same time, it will give you the press any key to continue message. Or type "(warning use this only for testing not actual programs as an antiviruses don't like it!!!!)" at the end of your main function but: (warning use this only for testing not actual programs as an antiviruses don't like it!!!!)
just use cin.ignore() right before return 0; twice
main()
{
//your codes
cin.ignore();
cin.ignore();
return 0;
}
thats all
you can try also doing this
sleep (50000);
cout << "any text" << endl;
This will hold your code for 50000m, then prints message and closes. But please keep in mind that it will not pause forever.
Here's a problem, not so obvious. Somehow I had added a debug breakpoint at the very last line of my program. } Not sure how I did that, perhaps with an erroneous mouse click while jumping between different screens. I'm working in VS Code.
And when I go to debug, the system jumps immediately to that breakpoint. No error message, no interim output, nothing. I'm like, how did the program rush thru all my set breakpoints? This took too long to figure out.
Apparently the system sees that last line breakpoint as a "first" stop. The simple fix? Delete that breakpoint, doh! (insert forehead slap here.)
All you have to do set a variable for x then just type this in before the return 0;
cout<<"\nPress any key and hit enter to end...";
cin>>x;

Is there a way to pause like system("pause")?

I've been looking for this on the internet for soooooo long. Is there a way you can press any key and it immediately stops the pause and carries on with executing the code but it doesn't show up the key you pressed on the screen (like system("pause"))?
People said cin.get() and stuff like that, however, if I use that, I have to press any key AND it displays on the screen and you have to press enter after that.
Since you're referencing system("pause") I guess you're using Windows, then you can use _getch to wait for any key.
Joachim Pileborg has already mentioned _getch as a Windows-specific technical solution.
However, that's a solution looking for a problem … because there's really no problem.
To see the last output from your console program, you can use any of these methods:
Run the program from the command line, e.g. an instance of Windows' standard [cmd.exe] command interpreter.
Run the program from an IDE, such that it stops at the end. E.g. in Visual Studio just use [Ctrl F5].
Run the program in a debugger, with a breakpoint on the closing } of main. E.g. in Visual Studio, add that breakpoint and run via keypress [F5].
Especially when you try the first bullet point, you will notice that having a _getch or system( "pause" ) or such at the end of the program, has no advantage and can be quite annoying!
I don't know about Windows (where apparently _getch() is the way to go) but on UNIXes you can set the standard input stream (file descriptor 0) into non-canonical mode using tcgetattr() and tcsetattr() to get the key immediately. To suppress the key presses from showing up, you'll need to also disable echoing:
termios old_tio, new_tio;
int rc = tcgetattr(0,&old_tio);
new_tio=old_tio;
new_tio.c_lflag &=(~ICANON & ~ECHO);
rc = tcsetattr(0,TCSANOW,&new_tio);
std::string value;
if (std::cin >> value) {
std::cout << "value='" << value << "'\n";
}
rc = tcsetattr(0,TCSANOW,&old_tio);
This code
first gets the current state of the terminal flags
clears the ICANON and ECHO flags
read hidden input (in this case a string but it can be an individual key, too)
restores the original settings
There is, unfortunately, no portable way of dealing with these setting, i.e., you will need to resort to platform specific uses. I think the use of tcgetattr() and tcsetattr() is applicable to POSIX systems, though.

system("pause") clarification

When i use system("pause"), then a line "Press any key to continue..." shows up on the screen.
This is iritating and makes reading the output quite cumbersome.
Is there some way to stop this from coming?
Do you mean that you want to press any key to continue but not to display the "Press any key to continue" on the screen? Try this getchar(); this will capture one character typing from keyboard and continue.
Rather than using platform dependent system("pause") you can use the platform independent std::cin.get() and if the buffer is messing with it, you can use:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n')
before hand to clear the buffer.
Assuming you're on Windows, replace the system("pause") with system("pause > NULL").
First of all, you should never use system("pause") because it is dangerous. Your code will be calling an external system procedure for no reason; and a cracker can find a way to substitute the "pause" command to other, making your program call the other program with your user permissions.
That said, you can avoid the message sending it to null device.
On Windows:
pause > nul
And if you want to be bold to make this awful system call portable, you can use:
on linux:
echo Press any key to continue ...; read x
Now you can apply the OR and AND (logic connectives) to both and make a system call that works on both systems:
void pause(void)
{
system("echo Press any key to continue . . . && ( read x 2> nul; rm nul || pause > nul )");
return;
}
Linux will create a temporary file called "nul" because it does not recognize this keyword. The null device on linux is /dev/null, not just nul. After that, the command will remove this temporary file with rm nul. So if you happen to have a file named nul on the same directory, be warned this command is not good for you (for yet another reason).
This command mimics the original. If you want to avoid the message, just remove the echo Pres... part of it.
Bonus:
Clear the terminal screen portably using system? (No, do not do this for the same reasons. Its dangerous.) But for tests purposes, you can use:
system("cls||clear");
Avoid pause. C is a language, one of the most powerful languages that there is. I'm sure there is a way to make a pause using only C (getchar() or scanf() for instance).
That line is part of the system("pause"). You can try a different method, such as getline(std::cin, variable) or cin.get().
Use
system("pause>nul")
It works perfectly for windows!

"Press any button to continue" in Visual Studio Express C++?

When creating an console application (blank document) how can I get the "Press Any Button To Continue" to automatically show up?
You can add it manually with a
system("pause");
*Be carefull, this is not portable (will work on windows, but might not work elsewhere)
When you run a console program in the IDE using "Start Without Debugging" (Ctrl-F5) you get the behavior you're looking for.
For some reason, when you start the program in the IDE under the debugger ("Start Debugging" or plain-old-F5) you don't get that prompt when the program ends. If you just want to be able to see the last bit of what's in the console window when run under the debugger, you can set a breakpoint on the return from main() (or the closing brace for main()).
There is no builtin function. However you can do a simple loop with kbhit() and getch(), like so:
#include <conio.h>
void main( void )
{
// Display your message here
for(;;)
{
while( !kbhit() );
if (getch() == 0x0D)
break; // Break on ENTER
}
// Continue on here
}
Adapted from http://support.microsoft.com/kb/44895
system("pause") is definitely what you were asking for, but using it is very bad practice. Consider just using cin.get() at the end and press enter.

Scanf with Signals

I have a signal that blocks SIGINT and basically says "Sorry, you can't quit.\n"
The issue is this can occur during a scanf.
When this occurs during a scanf, scanf takes in the printf as input.
How can I do a printf that will cause scanf to basically hit the enter key automatically. I don't care that I am getting bad input. I just want to programatically finish that scanf with a printf or something else.
Process:
scanf("get stuff")
-> User is able to enter stuff in.
-> SIGINT occurs and goes to my handler.
-> Handler says "Blah blah blah" to stdout.
-> Scanf has taken this blah blah blah and is waiting for more input.
How do I make it so that when I return scanf is finished (don't care what it has gathered I just want it to continue without user help).
EDIT: if I send two signals then the scanf terminates. I want to emulate the ending of the scanf somehow programatically.
Your question suggests you are confused - or perhaps English is not your native language.
I have a signal that blocks SIGINT and basically says "Sorry, you can't quit.\n"
What you might have is a signal handler that is set to respond to SIGINT. Further, you might be using the 'signal()' function to set the handler - but you should be aiming to use the POSIX standard 'sigaction()' function to set the handler instead.
The issue is this can occur during a scanf.
In context, 'this' is presumably an interrupt signal, typed by the user who wishes to stop your program. Be cautious about stopping people exiting a program with an interrupt signal; if you don't let them do that, they will be more brutal. That might mean they'll generate SIGQUIT (and perhaps a core dump) instead; if you block that too, there are a number of other tricks they can try until they get to the ultimate 'kill -9 pid' which your program will get no chance to react to.
When this occurs during a scanf, scanf takes in the printf as input.
This is confused...you are presumably implying that the output from a 'printf()' statement (presumably the one that says "You can't quit") is then being seen as input to the 'scanf()'? Which seems pretty improbable... It would require a very, very weird setup on the I/O of the process, and I'm still not convinced it can happen.
How can I do a printf that will cause scanf to basically hit the enter key automatically. I don't care that I am getting bad input. I just want to programatically finish that scanf with a printf or something else.
There are several possibilities - it depends in part on the O/S you are using (even if it is POSIX.) I don't use 'scanf()'; I find it too difficult to control. If your system resumes the reads after the interrupt handler returns, then you will have a difficult time. Sometimes, though, 'scanf()' will stop short and return the number of items it has processed. If the 'scanf()' you have does not terminate, then you will need to think about interposing a 'sigsetjmp()' in a function that simply calls 'setjmp()' and then invokes your function that calls 'scanf()'. Then your signal handler can use 'siglongjmp()' to return to that intermediate function:
sigjmp_buf trap;
int intermediary(int argument)
{
if (sigsetjmp(trap) == 0)
{
function_calling_scanf(argument);
return 0; // Success
}
// Report failure
return -1;
}
Your description continues:
Process:
scanf("get stuff") -> User is able to enter stuff in.
-> SIGINT occurs and goes to my handler.
-> Handler says "Blah blah blah" to stdout.
-> Scanf has taken this blah blah blah and is waiting for more input.
How do you know that scanf has read the 'blah blah blah'? It seems very, very improbable to me.
How do I make it so that when I return scanf is finished (don't care what it has gathered I just want it to continue without user help).
Use sigsetjmp().
EDIT: if I send two signals then the scanf terminates. I want to emulate the ending of the scanf somehow programmatically.
This is what indicates that you are using 'signal()' to set your signal handler and not 'sigaction()'. With 'signal()', when the interrupt occurs, the signal handler is set back to the default. With 'sigaction()', you have to request that behaviour; by default, the received signal (SIGINT) is blocked for the duraction and the signal handler remains in effect. If a second interrupt occurs while the first is running, the second is held up until the first handler returns (at which point the handler will be re-entered).
Don't use scanf as its buffering or retry code may get in the way. If you use a read(2) call it should return -1 with an errno of EINTR. Scanf may see that error and retry the read. You can always sscanf the data from the raw read.
This is assuming that QNX is POSIX compliant for read and you don't have the source for scanf for inspection.