新手C++程序员求助:如何实现非Y/N输入时重复询问是否继续计算
Hey there! I see where your issue is—your current code only checks if the user entered Y/y to continue the main loop, but it doesn’t handle invalid inputs (like typing "X" or a number) at all. Instead of repeating the question, it just exits the loop right away. Let’s fix that with a nested input validation loop, plus some input stream cleanup to handle messy user inputs properly.
Here's the revised code with fixes:
#include <iostream> #include <limits> // Needed for clearing input buffer using namespace std; int main() { int base, exponent; long int result = 1; char choice; int i; do { cout << "This program raises a number to a specific power." << endl; cout << "\nEnter a base integer greater than 1: "; cin >> base; cout << "\nEnter an exponent integer to raise that number to: "; cin >> exponent; // Reset result before each calculation (cleaner placement) result = 1; for (i = 1; i <= exponent; i++) { result = result * base; } cout << "\n" << base << " to the power of " << exponent << " = " << result << endl; // Nested loop to enforce valid Y/N input do { cout << "\nWould you like to make another calculation? Y or N: "; // Fix input stream state if it's in an error state cin.clear(); // Ignore all leftover characters in the buffer (like newlines or extra input) cin.ignore(numeric_limits<streamsize>::max(), '\n'); cin >> choice; // Alert user to invalid input if (!(choice == 'Y' || choice == 'y' || choice == 'N' || choice == 'n')) { cout << "Oops, that's not a valid choice! Please enter Y or N." << endl; } } while (!(choice == 'Y' || choice == 'y' || choice == 'N' || choice == 'n')); cout << endl; } while (choice == 'y' || choice == 'Y'); cout << "Good bye, then. Have a good day.\n" << endl; return 0; }
Key changes explained:
- Added
<limits>header: Required to usenumeric_limitsfor properly clearing the input buffer. - Nested
do-whilevalidation loop: This loop will keep prompting the user until they enter a valid Y/N—no more accidental early exits from invalid inputs! - Input stream cleanup:
cin.clear(): Resets the input stream’s error state. If the user enters something non-character (like a number),cingets marked as "failed"—this fixes that so we can read input again.cin.ignore(...): Throws away all leftover characters in the buffer (including the newline from pressing Enter) to avoid interfering with future input reads.
- Moved
result = 1to calculation start: A small cleanup to ensure the result is always reset before computing a new power, making the code more robust.
Bonus note:
Right now, your power calculation only works for positive exponents. If you want to handle exponents of 0 (result should be 1) or negative exponents (result would be a fraction), you could add extra logic for those cases later—but that’s optional based on your original requirements.
内容的提问来源于stack exchange,提问作者CLK

