C++ newbie coming from python. When I compile and run the following code, then press Ctrl+C before inputting anything, I see the terminal still prints You entered 0^C
.
#include <iostream>
int main()
{
int num1;
std::cin >> num1;
std::cout << "You entered " << num1 << "\n";
}
First of all, coming from Python, I don't see the benefit of not throwing an error when std::cin
receives no input, and don't understand the motivation of why the program is allowed to continue to following lines. What's the reasoning for not throwing an error when std::cin
doesn't work?
Second, is this behavior suggesting that num1
has a value of zero before initialization? My initial thought was that perhaps num1
is given a default value of 0
even though it wasn't initialized. However, the following code seems to break that guess: when I hit Ctrl + C after compiling and running the code below, the screen prints You entered 24^C
, or sometimes You entered 2^C
, or sometimes just You entered ^C
. If I rebuild the project, a different number appears.
#include <iostream>
int main()
{
int num1, num2, num3;
std::cin >> num1 >> num2 >> num3;
std::cout << "You entered " << num1 << ", " << num2 << ", " << num3 << "\n";
}
I thought this might have something to do with the buffer, but adding std::cin.ignore()
didn't prevent this behavior.
Is this a C++ thing or does it have to do with how the OS handles keyboard interrupts? I feel like I might have seen numbers proceeding the ^C
while interrupting python scripts before, but didn't think about it.