cin >> fails with bigger numbers but works with smaller ones?

Try:

std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>

int on your system is likely a 32-bit signed two’s complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can’t be properly represented by int. cin fails, alerting you of the problem.

long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can’t represent negative numbers, so it’s a trade-off.

Leave a Comment