Home > Back-end >  Keyboard interrupt adding numbers to terminal before closing
Keyboard interrupt adding numbers to terminal before closing

Time:12-04

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.

CodePudding user response:

num1 is not initialized, which means it contains whatever random value was in memory.

When control-c is pressed, std::cin >> num1; fails. Then next line will print some random value that was in num1 earlier.

The correct version should be

int num1 = 0;
if (std::cin >> num1)
    std::cout << "You entered " << num1 << "\n";

You can use std::cin.ignore and ctd::cin.clear to clear the end of line. That's in case, for example, the user is supposed to enter integer, but enters text instead.

In the example below, if you enter text when integer is expected, then cin will keep trying to read the line, unless the line is cleared.

for (int i = 0; i < 3; i  )
{
    std::cout << i << " - Enter integer:\n";
    if (std::cin >> num1)
    {
        std::cout << "You entered " << num1 << "\n";
    }
    else
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}
  • Related