What is happening is that cin >> n
is consuming the +
, because that could be part of a valid integer (e.g. +5
); but then the integer input fails because it wasn't followed by a digit.
With stream input it cannot "look ahead", it has to make a decision on a character by character basis. This is why strtol
, or std::stoi
etc. are more reliable than reading an int via operator>>
.
The C++14 text [facet.num.get.virtuals]/3 stage 2
specifies that the +
should be consumed by the invalid read; however library implementations often don't exactly follow the standard with respect to reading numbers via operator>>
because the standard is defective and changes a lot. So you may or may not find other compilers behaving differently.
To avoid this situation entirely I'd suggest taking a different approach; e.g. reading a string
every time, and then making other checks such as std::stoi
or otherwise to see if that string was an integer.