dimanche 26 novembre 2017

Why does throwing an exception after Ctrl+C freezes cmd?

I came accross this problem while writing a console application with input parsing in C++11 for a school assignment.

I'm using the MinGW compiler on Windows 10. When I run this program in cmd and hit Ctrl+C the command line freezes, keeping the process running, not responding to console inputs.

Minimal, Complete, and (Verifiable?) example

#include <iostream>
#include <string>
#include <sstream>
#include <stdexcept>

int main()
{
    std::string line;
    getline(std::cin, line);

    if (!std::cin.good()) {
        std::ostringstream message;
        message << "Unexpected input stream state \"" << std::cin.rdstate() << "\".";
        throw std::invalid_argument(message.str());
    }

    return 0;
}

It HAS worked1 once or twice, but I could not reproduce it, because it broke the second time I ran it (without recompiling or changing anything). I'm not sure if anyone can reproduce the problem.

If I delete the throw, it works.

Also, if I output a text with cout right after getline, it works too.

Why is this happening?

1 working - the expected behaviour is to immediately close down the program when hitting Ctrl+C (without throwing the invalid argument exception).

Aucun commentaire:

Enregistrer un commentaire