I am trying to build a simple cpp code to check whether an input number is an even number bigger than 2 (trying to experimentally solve codeforce's watermelon using cstdint). Problem is, when i use int_fast8_t as the data type for the input interger, the code somehow prints "yes" when i put in 2 as an input. This problem is nonexistent when I use basic int data type. Any ideas on why this happens?
the code is as below:
#include <cstdint>
#include <iostream>
int main(int argc, char* argv[]) {
int_fast8_t input;
std::cin >> input;
if ((input % 2 == 0) && (input > 2)) {
std::cout << "YES";
} else {
std::cout << "NO";
} std::cout << "\n";
return 0;
}
input: 2
expected output: NO
actual output : YES
The problem is that
int_fast8_tis defined as a type alias forsigned char. This isn't required by the C++ standard, but it's what your standard library chose to do.You could verify this by looking at the source code of your standard library, or with:
As a result, what you're actually doing is:
This calls
operator>>(std::istream&, signed char&), which is a special overload that treatssigned charlike a character, instead of an integer.When providing
2as user input, this is actually the ASCII/UTF-8 character'2', which has the numeric value50.This passes the test
input % 2 == 0because50is divisible by2, and also passes the testinput > 2because50is greater than2.Solution
To fix this, use
intinstead; at least for user input.See Also