1

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.

TimH
  • 423
  • 4
  • 14

1 Answers1

2

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');
    }
}
Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
  • Thank you for your response. So uninitialized variables in C++ are given random values? If so, why are there cases where the output shows no number before `^C`? Also, it looks like your code is suggesting that `std::cin >> num1` gives an output that can be interpreted as a boolean that represents its success or lack thereof. Why not just crash or throw an error? That seems sketchy to keep running despite that line failing to work. Thanks for your help. – TimH Dec 03 '21 at 02:24
  • 1
    @TimH: [What will be the value of uninitialized variable?](https://stackoverflow.com/questions/11233602/what-will-be-the-value-of-uninitialized-variable) (This C question also applies to C++.) – Andreas Wenzel Dec 03 '21 at 02:32
  • 2
    @TimH: The line `if (std::cin >> num1)` is equivalent to `if ( ! (std::cin >> num1).fail() )`, as the former is calling [`std::istream::operator bool`](https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool). – Andreas Wenzel Dec 03 '21 at 02:37
  • @AndreasWenzel Thanks very much. So allowing `std::cin` to fail and continue without crashing gives the programmer the ability to catch bad input without making the program crash? Is that the benefit of C++ being designed that way? – TimH Dec 03 '21 at 02:40
  • 1
    @TimH some c++ classes do throw exception, you can catch it and handle it, or exit the program gracefully. It doesn't have to end in program crash. In this case, as you noted, it doesn't throw exception, just success or failure. – Barmak Shemirani Dec 03 '21 at 02:45