__int16_t
is presumably a (compiler-specific) type that is a 16-bit signed integer. scanf()
does not generally support such compiler-specific types (and, if it does, it will require a format specifier that is specific to your compiler and library).
In the following, I assume a compiler that supports __int16_t
as a 16-bit signed integral type, and scanf()
does not provide any way to read one.
long int some_int; // range at least [-2147483647,2147483647]
__int16_t a;
if (scanf("%ld ", &some_int) == 1)
{
// report error if some_int outside range a __int16_t can represent
a = some_int;
}
else
{
// an error occurred
}
I don't use int
and the %d
format specifier in the above, because the C++ standard only requires an int
to be able to represent the range of -32767
to 32767
(albeit permitting a larger range). It is conceivable that int
for your compiler can represent the range -32678
to 32767
but that an __int16_t
represents the range -32767
to 32768
. In such a setting, the above code may not handle input of 32768
correctly if it uses int
instead of long int
.
Personally, I'd probably try using a C++ istream
(e.g. std::cin >> a
) instead of C's scanf()
because, practically, it is likely it likely to work. The reason is that, if an implementation which supports a type like __int16_t
, the effort to have included support in istream
for it is less than the effort to support it in scanf()
.