Q:

Output buffer and Cntrl+C to exit program

If I have a simple program like;
#include <iostream>
#include <fstream>
using namespace std;

int main(){

    ofstream output("huh.txt");

    int a;

    while(true){
         cin >> a;
         output << a << endl;
    }

}

If I input 
2
3
4
5
6
7

And then press Cntrl+C to exit the program, what will be saved in huh.txt is:
2
3
4
5
6
7
7
7
7
7

My main program is similar to this. It wants continuous input from the user to place in to an output file. The only problem is when exitting using Cntrl+C the output often duplicates like shown above. How exactly are Cntrl+C and "output"'s buffer being treated such that 7 is output 4 more times than usual? And is it generally a bad idea to exit a program through Cntrl+C?

A:

I could reproduce the case on windows with MSVC 2013, but not on linux.   
Ctrl+C causes cin>>a to fail and the end of file flag to be set.  Thus a is not overwritten.  As you loop forever without looking at  cin's state, you continue to output the last (unchanged) valid value.  
Ctrl+C causes at the same moment the programme to be interupted. It's almost immediate, but only almost. For instance, in windows, the processing of Ctrl+C is done by launching a separate thread, leaving the main thread to continue what he's doing unitli it's over.   So the endless loop will be interupted by the termination signal, but it could still perform some iteration.  
The easiest way to avoid this problem is to process correctly input errors:  
while (true){    
    if (cin >> a)
        output << a << endl;  // output only if input was successful
}

