How do I force to input before termination?
Here is an excerpt of my code, where the problem lies.
long long user_largest_plus;
long long user_largest_minus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus;
//cout << endl;
// cout << "Input the largest-1 in decimal: " << e开发者_运维技巧ndl;
cin >> user_largest_minus;
cout << endl;
cout << "In decimal plus: " << user_largest_plus;
cout << endl;
cout << "In decimal minus: " << user_largest_minus;
As soon as I input 9223372036854775808 to user_largest_plus
, the execution would terminate. That is, I wouldn't be able to input for user_largest_minus
.
I am using Code::Blocks, MinGW compiler.
Is it because I just overflowed the variable, and the error triggered this termination. Any work around?
By the way, that number is 2^63 - 1
, maximum number that I can store.
Thanks
Try replacing
cin >> user_largest_plus;
with
if( !( cin >> user_largest_plus ) ) {
user_largest_plus = 0;
cin.clear();
cout << "Bad input. Using zero instead\n";
}
When the input text is not a valid long long
, two interesting things happen:
user_largest_plus
is never set, and- the
bad
bit is set incin
.
The provided code sets some value to user_largest_plus
to avoid undefined behavior, and clears the bad bit, so cin
can still be used.
Assuming it is because the entered number is to big (and to prevent bugs when the user enters APPLE
as the size, you should do something like this:
string user_largest_plus_string;
long long user_largest_plus;
cout << "Input the largest+1 in decimal: " << endl;
cin >> user_largest_plus_string;
user_largest_plus = atoi(user_largest_plus_string.c_str());
if (user_largest_plus == 0)
throw std::runtime_error("User entered something besides a number!");
cout << "largest+1 is now " << user_largest_plus << "." << endl;
精彩评论