Jun-18-2020, 09:08 PM
Sorry. It's been too long since I've done C++, and your code didn't immediately compile. So I can't tell you why the C++ would accept a character. (I think it shouldn't since x is declared int).
But in the C++ code, cin is returning a value representing success, not the value of the input (that goes to x). So entering a "false" value still enters the loop.
In python, the input returns the value that was entered. This is passed to int() that tries to convert it. So if you enter a zero, it becomes the number zero, and that is false. There is no question of the input failing. It will block, succeed, or throw an exception.
In C++ a character can't be sent to the declared int variable, so the >> operator fails and returns false to the test.
In Python, int() doesn't fail. It either succeeds or throws an exception. You can catch the ValueError exception in a try/except block if you want to continue even when a non-integer is passed in.
But in the C++ code, cin is returning a value representing success, not the value of the input (that goes to x). So entering a "false" value still enters the loop.
In python, the input returns the value that was entered. This is passed to int() that tries to convert it. So if you enter a zero, it becomes the number zero, and that is false. There is no question of the input failing. It will block, succeed, or throw an exception.
In C++ a character can't be sent to the declared int variable, so the >> operator fails and returns false to the test.
In Python, int() doesn't fail. It either succeeds or throws an exception. You can catch the ValueError exception in a try/except block if you want to continue even when a non-integer is passed in.