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

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
// ...
}

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 determine I've reached EOF with a non coded file?

I've looked up several instances in EOF, but in all instances EOF is being used on a file that is part of the program, for example:
std::fstream myFile("file.txt", std::ios::in);
while(!myFile.eof()) {
/*program*/
}
However in this instance, I'm not using a file as part of the code. I'm just using basic cin commands. There's a command to quit, but let's say a user runs the program like this:
./program <myFile.txt> myOutput
Let's say that myFile had these commands in this:
add 1
add 2
delete 1
print
That's all fine, but they forgot to add a quit command at the end, so the code won't stop. So how do I get the code to detect EOF in this situation and stop?
The correct way to detect end-of-file is to check each input operation for success.
For example, with getline you'd use
std::string line;
while (std::getline(std::cin, line)) {
// do stuff with line
}
Or with >>:
while (std::cin >> x) {
// do stuff with x
}
This applies to all input streams, whether they're from files (fstream) or e.g. cin.
End of file (EOF) means there is nothing more to read from the file buffer, it’s not something one puts explicitly at the file itself.. you should still get there fine with your code
Another way is to read the buffer until there are no more bytes to read there

Read information that has been couted to the terminal

I am trying to figure out how to read information from the terminal or console, (I am using ubuntu)
I am not looking for cin, or readline.
I don't want user input, instead I want a program that will read text that is written in the terminal by cout, put_char etc... How can this information be accessed by a C++ program?
edit:
say I have a program that
int main(...)
{
cout << blahblahblah;
....
}
how can I read the information that was sent to the terminal?
int someFunc()
{
someIostream terminal;
string = terminal.readline();
}
Or as another example
suppose I have some user who has been running things on their terminal
and I want to see everything they typed in before running my program

Preventing printf from spamming the console while getting user input

I am coding a console application on windows.
I made it multithreaded so it can print status to console while I am receiving input from the prompt.
But when printf() gets called while I am typing the command, I see the output intersecting with what I have typed.
How can I get around this problem? is there a way to keep the input line separate?
I am using getline(cin, strcommand); to collect input data
standard output is a mutual exclusive resource, so it cannot be both used by input and output at the same time.
In your problem, input and output intersect with each other, so i think you can use a buffer to store your log created by the print status thread while you are inputting. When input is over, you can check if there are logs not yet be printed.
while(cin >> x) {
//get output buffer mutex
if(log_exist)
//print the log
//clear the flags
//release output buffer mutex
}
I thingk you just need to end the line with << endl; at the end of your cout. then the input will be under the output.

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