Prevent console from closing - c++

I tried std::getchar();, cin::get(); and system ("sleep");, but nothing stops the console from closing, because it seems, that all of these functions misinterpret the pressed enter key that was supposed to confirm input for scanf. How can I prevent the console from closing with a "Press enter / any key to close" behavior after scanf? I don't want to use functions stopping the console totally from doing something for some time (like sleep) or non-portable functions (like system ("sleep")), unless such functions are the only ways.
int main () {
wchar_t *user = new wchar_t[30];
wscanf (L"%30ls", user);
// Process data... (very short time)
std::getchar ();
return 0;
}
IDE: Visual Studio 2013 (12.0) Express
I don't know the compiler. I created an empty C++ project and didn't change any settings.

Do it like this:
// do your stuff here
// prevent console from closing
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.get();

Use system("pause"); at the end of main() function.

Related

Minimal solution to use wxWidgets: wxTextControl to emulate a C++ std::cin and std::cin(getline) stream

I have transcribed a c++ console app to GUI using wxWidgets. Most of my functions were written for the commandline flow. I am creating handles and additional code to interface GUI with the functions. I have emulated a console for output stream, which works good (using wxStreamToTextRedirector). However, I can't find a simple solution to take user input from a textcontrol and substitute the std::cin command in cases like the code below. Event handlers and GUI controls for my frame are in MainFrame.cpp and object data and functions in another Data.cpp
I have a function in Data.cpp which will be called on a button press event from MainFrame.cpp:
bool Data::run_yn_prompt()
{ //Run Y or N input prompt
do {
std::string input = "";
std::cout << "\n Input Y/y to proceed, N/n to cancel:"; **//OUTPUT TO DISPLAY CONSOLE**
std::getline(std::cin, input); **//Need to fetch wxTextCtrl input at this point only**
std::cout << input;
if ( (input=="Y") || (input=="y") ) return true;
if ( (input=="N") || (input=="n") ) return false;
} while(1==1);
}
The problem is I need the input to be fetched only after:
the previous std::cout is run and
the user enters the input and presses ENTER (to be signaled by wxEVT_TEXT_ENTER event handler)
The only way I guess I could do it is by adding a lot of conditionals and boolean flags to watch for user input and enter press. Is there any simple strategy to make this work? My goal is not to publish this app, but learn to get wxWidgets elements to work as per my need. I have so many std::cin in the middle of my code like this. This problem has stopped me from moving forward with wxWidgets. And I would like to keep everything in a single frame without additional dialogs.
The only way to preserve the code using std::cin in a GUI program is to use modal dialogs for text entry (e.g. wxGetTextFromUser()) instead. This is not going to be nearly as convenient for the user as using a text control inside the main program window, but it's the only way to preserve the existing control flow.

How to use CTRL+C to stop getting input from the user?

I wanted to write a console notebook application which gets text from the user and saves it in .txt file. So, for inputting the text, I am using a while-loop:
while (getline(std::cin, line)) {
myfile << line << "\n";
}
If the user is done writing the text, he/she must do something so the loop breaks. I have found something called signal handling, but do not know how to implement it in my code. I also tried SetConsoleCtrlHandler from Microsoft. How can I get the use of it, or are there any other ways to do the given task?
Ok, If you need only Ctrl+C as end of input:
Use SetConsoleCtrlHandler to detect Ctrl+C and set stop_flag (std::atomic_bool) for input stop.
Your input cycle should be like this:
Use while (!stop_flag) {
if (_kbhit()) {
auto symbol = _getch();
// Process input char-by-char
// ...
}
// May be add some sleep for 20 ms
// ...
}

getch() showing prototype error

I have just started learning c++ and I want the programme to stay open after the result is displayed. So I used getch(); and c++ is showing that it should have a prototype. What does it mean? and how do I resolve this>
it means one of the followings:
you are programming under DOS and forgot to include conio.h (https://en.wikipedia.org/wiki/Conio.h). Possibly you copied a source from an older textbook, since conio.h is a very old concept. What sources do you use for learning? I'd recommend one from: The Definitive C++ Book Guide and List
You are programming under Linux and you forgot to include curses.h (http://linux.die.net/man/3/getch)
Include:
1) <conio.h> on Windows.
2) <curses.h> on UNIX
Looks like you only want to PAUSE your console application on the screen. Use this#include <stdio.h> and try getchar(); instead of getch(); or simply system("pause"); or cin.ignore() will do the job for you.
Also, "Start without Debugging" using Ctrl-F5 will allow you to Press Any Key To Continue at the end of your program. This way it won't close until you press some key and the console will pause on the display screen.
If you're on Windows then getch is a function from the Windows-only <conio.h> library. You need to include it (#include <conio.h>).
It's possible only on Windows.
Also, getch() is deprecated.
Use _getch() instead.
If you're on GNU+Linux, then getch is a function from the <curses.h> library. You need to include it (#include <curses.h>).
The objective as I understand is :
I want programme to stay open after the result is displayed
Why not do it the typical c++ way?
#include<iostream>
int main(void)
{
int i;
char ch;
std::cout<<"Enter any character : ";
std::cin.get(ch); // For testing enter a string at this step say "String"
/* The input to cin is line-buffered, so after reading 'S' to ch,
* the remaining "tring" is still in the buffer.
*/
std::cout<<"Entered character : "<<ch<<"\n";
while(std::cin.get()!='\n')
;;
/* cin.get() is an overloaded function in the istream class.
* If no arguments are passed to 'get()' this function reads single next character
* In essence, we wait for the cin.get() to clear the buffer that is
* read all characters including '\n'
*/
std::cout<<"Press any key to continue..\n";
std::cin.get();
/* Since we have already cleared the buffer using the loop
* 'get()' expects us to enter a character this time
*/
return 0;
}

C++:can the condition state of cin stream be recovered after entering EOF

Here is my code for test:
#include<iostream>
using namespace std;
istream& func(istream &);
int main()
{
if(func(cin))
cout<<"good"<<endl;
return 0;
}
istream& func(istream &is)
{
int num;
is.clear();
auto old_state = is.rdstate();
while(is>>num)
cout<<num<<endl;
is.setstate(old_state);
return is;
}
The problem is:if I enter a char or the mark of EOF(ctr_z in my system) to break the while loop,then the program terminates directly.I was expecting that the cin stream can be reset to a normal state and be returned:
if(func(cin))
cout<<"good"<<endl;
But I can't get that output when program ends.
So what's wrong with my understanding?
You need to ignore the eror and then clear it. So as an example you just need to change your while loop to something like this:
while(true)
{
if(is>>num)
cout<<num<<endl; //if cin is numeric
else // we have an error
{
is.ignore(); // ignore the last error (else your program will run crazy)
is.clear(); // clear the state
break; // terminate console reading
}
}
It's because setstate does not really clear the old flags (read the linked reference to see why)
If you want to completely reset the flags then you need to use the clear function. Not that I really recommend it though, as it gives you a false state of the stream. Instead you should explicitly check the state.
The state can be recovered after an invalid input: failure to parse the input according to the expected type just sets std:: ios_base::failbit which can be clear()ed. Since the character causing the problem is not removed, you'll probably need to get rid of it (e.g. using ignore()) or parae the data differently.
Although EOF is also just a flag (std::ios_base::eofbit) clearing it in general won't recover the from having reached the end of the stream. Specific streams may have a way to carry on reading but the console is likely to be disconnected after an end of stream indicator (e.g., Ctrl-D or Ctrl-Z). Depending on the system it may be possible to create a new connection to the console, e.g., by opening a file stream to /dev/tty.
If you really want to use control characters to indicate special processing you'll need to disable the default processing and manage them within the program. On UNIX systems you'd set the stream into noncanonical mode using tcgetattr() and tcsetattr(). Once this is done all characters entered are seen and can be processed accoringly, probably in a custom stream buffer. I don't know how to do something similar on other systems.

What code should be used instead of getche in c++

I am new to c++ ,
What code should i write to make the screen stand still. I use
getche();
in c language. but instead of getche() what should i use in c++;
I tried
std::cin.get();
but the console windows displays and then goes off quickly.
the console windows displays and then goes off quickly.
It seems that you have something in your buffer, and cin.get is reading that as a character. For example:
int i = 0;
std::cin >> i;
std::cin.get();
When you enter number and press Enter, cin >> i will consume the number, but it will leave \n character (which comes from Enter keystroke) in the buffer which will be read by std::cin.get() without waiting for the user to enter new data.
In order to make this example to behave like we want, we need to empty the buffer before calling std::cin.get():
int i = 0;
std::cin >> i;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get();
std::numeric_limits is defined in <limits> header file.
In Windows, I usually uses system("pause");, which call the OS's pause command, to prevent the console window from being closed after the program terminates. This commands displays a nice message and wait for any key :).
Press any key to continue . . .
I don't know if the command exists in the other OSes or not, nor I don't know if it is what you're trying to archive :).
The function is in the cstdlib or stdlib.h header file
Last but not least, it's not really a good idea to call getch() at the last line of code to prevent the console from being closed. But if you really prefer this way, I suggest to use something like
std::string temp;
std::cin>>temp;
At the ends of your main function, just before return statement.
Just include <stdlib.h> and in main method use system("pause") your console window will remain still.
Please use the following
getch()