Getch结合while循环触发循环内容执行两次问题求助
getch() Picking Up Spaces/Newlines in Your Loop Hey there! I totally get how frustrating it is to hunt for solutions when you're not a full-time coder—been there, done that with side projects too. Let's break down this getch() issue you're dealing with.
Why This Happens
You’re spot-on about the root cause: unlike cin which automatically skips whitespace (spaces, newlines, tabs), getch() reads every single character the moment it’s pressed. That means accidental spaces, hitting Enter, or even tabbing will trigger your input handling when you don’t want it to.
Simple Fix: Filter Out Unwanted Characters
The easiest way to fix this is to add a loop that keeps calling getch() until it gets a character you actually care about. Here’s how to slot this into your existing code structure:
#include <conio.h> // For Windows getch()—adjust if using Linux ncurses #include <iostream> // Add this if you need to clear leftover buffer later // #include <limits> using namespace std; int main() { int roundNum = 0; while (roundNum <= 20) { roundNum++; cout << "Round " << roundNum << ": Enter your input...\n"; char userInput; // Keep reading until we get a non-whitespace character do { userInput = getch(); // Skip spaces, newlines, carriage returns, and tabs } while (userInput == ' ' || userInput == '\n' || userInput == '\r' || userInput == '\t'); // Now handle your valid input here! cout << "You selected: " << userInput << "\n"; } return 0; }
Extra Tips
- If you used
cinanywhere before this loop, there might be a leftover newline stuck in the input buffer thatgetch()will pick up first. Fix that by adding this line right before yourgetch()loop:cin.ignore(numeric_limits<streamsize>::max(), '\n'); - If you’re on Linux instead of Windows,
getch()isn’t part of the standard library—you’ll need to use thencurseslibrary, but the filtering logic stays exactly the same.
内容的提问来源于stack exchange,提问作者Kaninstek

