如何优化这段C++代码避免重复逻辑,并处理输入异常?
Fixing Your Input Crash & Reducing Code Duplication
Let's break this down into two main parts: fixing that annoying input error, and cleaning up duplicated logic to make your code easier to work with.
1. Squashing the Input Exception
The crash happens because when you prompt for an upgrade option after typing "upgrade", you're using cin >> upgr to read an integer. If the user enters anything that's not a number (like "abc" or even "2"), here's what goes wrong:
cinenters a failed state because it can't parse non-numeric input into an integer.- After that, all future
cincalls will skip execution entirely, making your program loop without responding to input.
Here's how to fix it:
- Always check if
cinsucceeded after reading input. - If it fails, reset the error flag and clear out the invalid input from the buffer.
- Add a fallback message for when the user enters a valid number that's not 1.
2. Cutting Out Repetitive Logic
Your code repeats power*3 multiple times (calculating tapcost, checking if money is enough). This is a problem because if you ever want to change the cost formula (like making it power*4), you'd have to update it in every spot. Instead:
- Calculate the upgrade cost once and store it in a variable (you already have
tapcost, let's use it consistently). - Use
else ifinstead of separateifstatements forwaychecks—this avoids unnecessary checks once a match is found.
Refactored Full Code
#include <iostream> #include <string> #include <limits> // For clearing invalid input using namespace std; int main() { int power = 1; int money = 0; // Added initialization (you likely missed this in your original code) string way; int upgr; while (true) { // More readable than "1 == 1" int upgradeCost = power * 3; // Calculate once, reuse everywhere cout << "Type upgrade/buy/a" << endl; cin >> way; if (way == "upgrade") { cout << "1. A Power (Costs: " << upgradeCost << ")" << endl; // Check if input reading succeeded if (!(cin >> upgr)) { cout << "Please enter a valid number!" << endl; cin.clear(); // Reset cin's error state // Clear all invalid input from the buffer cin.ignore(numeric_limits<streamsize>::max(), '\n'); continue; // Skip to next loop iteration } if (upgr == 1) { if (money >= upgradeCost) { power++; money -= upgradeCost; cout << "Power upgraded! New power: " << power << endl; } else { cout << "You can't afford that!!!" << endl; } } else { cout << "Invalid option! Please enter 1 to upgrade." << endl; } } else if (way == "a") { money += power; cout << "Money increased! Current money: " << money << endl; } else if (way == "buy") { // You included this in the prompt but had no logic—add your buy code here! cout << "Buy functionality not implemented yet." << endl; } else { cout << "Invalid command! Please type upgrade/buy/a." << endl; } } return 0; }
Key Improvements:
- Input Safety: Added checks for non-numeric input, resets
cinstate, and clears invalid input to prevent crashes. - No Duplication:
upgradeCostis calculated once and reused, so changing the cost formula only needs one edit. - Readability: Replaced
1 == 1withtrue, addedelse ifchains, and added clear feedback for all invalid inputs. - Uninitialized Variables: Fixed missing
moneyinitialization (a common oversight that could cause weird behavior).
内容的提问来源于stack exchange,提问作者Alpha Reaper
相关产品推荐
相关产品推荐

