0

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?

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Did you try just doing `ctrl+c+enter`? – NathanOliver Jan 13 '20 at 14:48
  • @NathanOliver yes it is just terminating the entire program – Asadbek Khasanov Jan 13 '20 at 14:50
  • Entering EOF into stdin may also be a possibility: https://stackoverflow.com/questions/28216437/end-of-file-in-stdin – Andreas Wenzel Jan 13 '20 at 14:50
  • Oh, I bet you need to clear the error state from the stream after the loop. – NathanOliver Jan 13 '20 at 14:51
  • 2
    Note that Ctrl + z (Windows) or Ctrl + d (Linux) "naturally" signal EOF on standard-in (which makes `getline` fail). Linux console users usually know about Ctrl + d, it could be that your program needs to remind Windows users about the Ctrl + z option... -- I understood your question to ask for Ctrl + c *specifically*, hence this is not an answer. – DevSolar Jan 13 '20 at 15:08
  • Many Windows console users are aware of Ctrl+c, and expect it to end the whole application, not just input. I second @DevSolar's recommendation to use Ctrl+z. – Allison Lock Jan 13 '20 at 16:02

1 Answers1

0

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
  // ...
}
Evgeny
  • 1,072
  • 6
  • 6