scanf() is not for reading input, it's for parsing input:
scanf() is not a function I use or suggest for reading input (it is meant to parse formatted data), but I understand that fgets() + snprintf()/strtol()... would add more complexity and function calls.
The least that can be done is:
if (scanf("%d", &n) != 1) {
fprintf(stderr, "Error: invalid input.");
return EXIT_FAILURE; // <cstdlib>
}
Note that if the input exceeds the maximum value that an int can hold, the behaviour is undefined. (There's no redemption once undefined behavior has been invoked, you can't possibly avoid this. You can not somehow magically go back in time and fix things once the damage has been done.)
scanf() is defined by the ISO C Standard, which says (C11 7.21.6.2 The fscanf function /10):
If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
Same for C18, and C23/C24.
Also note that if the conversion failed, n would remain uninitialised, but the behaviour wouldn't be undefinedundefined per se, because its address has been taken, assuming it doesn't have a trap representation, in which case the code will always invoke undefined behaviour. Otherwise, if there are no trap representations, the variable takes an unspecified value.
Though your code may not invoke undefined behavior, the answer would be incorrect because you'd be processing something that wasn't what was provided as input.
Aside: It is more conventional to use the the C++ counterparts of the C headers (they're prefixed with c, and .h is left off). Unqualified scanf() comes from the C compatibility header <stdio.h> - when using the C++ header <cstdio> one should use standard-namespace std::scanf(). Same goes for printf().
See: (Why) is using an uninitialized variable undefined behavior?.