Блог пользователя Krktv

Автор Krktv, история, 9 лет назад, По-английски

Hey codeforces! One day I launched MinGW Studio and checked this simple code:

#include <iostream>
using namespace std;
int main() {
    int n = 50;
    cin >> n;
    cout << n;
    return 0;
}

I wrote 'z' on the console and saw '50'. Nothing strange. But when I did the same on the last version of CodeBlocks, I saw '0'. Can someone explain me what exactly happens in there and why it happens in CodeBlocks and doesn't happen in MinGW Studio?

  • Проголосовать: нравится
  • -5
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится +37 Проголосовать: не нравится

Let's read the fabulous manual. First go to documentation on operator>>. It says:

After constructing and checking the sentry object, which may skip leading whitespace, extracts an integer value by calling std::num_get::get().

Follow the link to documentation on std::num_get::get(). It describes the process of parsing in details. In particular, section 2 says:

In any case, the check is made whether the char obtained from the previous steps is allowed in the input field that would be parsed by std::scanf given the conversion specifier selected in Stage 1. If it is allowed, it is accumulated in a temporary buffer and Stage 2 repeats. If it is not allowed, Stage 2 terminates.

Clearly, the string "z" cannot be parsed by scanf so Stage 2 terminates and no characters are accumulated. Section 3 says:

The sequence of chars accumulated in Stage 2 is converted to a numeric value

The input is parsed as if by std::scanf with the conversion specifier selected in Stage 1 (until C++11)

The input is parsed as if by std::strtoll for signed integer v, std::strtoull for unsigned integer v, or std::strtold for floating-point v (since C++11)

So we parse the sequence of accumulated characters (the empty string), and this parsing must fail. The way it is parsed depends on the standard.

Documentation on scanf doesn't specify what happens to 'receiving arguments' in case of parse error, and I don't have the text of the standard here. But on my compiler the receiving argument doesn't change, and you observed it in 'MinGW Studio'.

Documentation on strtoll, on the other hand, says:

If no conversion can be performed, ​0​ is returned.

which is exactly what you observed in CodeBlocks.