在C++ int main()的do-while循环中添加退出功能遇阻求助
Fixing Your Program's Exit Functionality with do-while and bool Control
Hey there, let's get that exit feature working properly for you! I can tell you're on the right track using a bool keepGoing variable with a do-while loop to keep your program running, but the issue with detecting 'q' or "exit" comes down to a few common C pitfalls. Let's break this down and fix it step by step.
The Core Issues You're Facing
- Comparing strings with
==: In C, you can't use==to check if two strings are equal—this compares the memory addresses of the char arrays, not their actual content. You need to use thestrcmp()function from<string.h>instead. - Invalid character constants: Writing
'quit'is a multi-character character constant, which has undefined behavior in C. Strings like "exit" need to be wrapped in double quotes ("exit"), not single quotes. - Unprocessed newline characters: If you're using functions like
scanforfgets, they might leave a newline in the input buffer or include it in your input string, which breaks string comparisons.
Working Example Code
Here's a complete, tested implementation that handles both 'q' (single key press) and "exit" (full string input) to exit the loop:
#include <stdio.h> #include <stdbool.h> #include <string.h> #include <ctype.h> int main() { bool keepGoing = true; char input[256]; // Buffer to store user input (size it appropriately for your use case) do { // Prompt the user for input or exit options printf("Enter your command (type 'exit' or press 'q' to quit): "); // Use fgets to safely read input (avoids buffer overflow issues with scanf) if (fgets(input, sizeof(input), stdin) == NULL) { // Handle unexpected input errors (like EOF from Ctrl+D/Ctrl+Z) keepGoing = false; break; } // Remove the trailing newline character added by fgets (if present) size_t inputLength = strlen(input); if (inputLength > 0 && input[inputLength - 1] == '\n') { input[inputLength - 1] = '\0'; } // Check for single 'q' input (case-insensitive, so 'Q' works too) if (strlen(input) == 1) { char inputChar = tolower(input[0]); if (inputChar == 'q') { printf("Exiting program via 'q' key...\n"); keepGoing = false; continue; } } // Check for "exit" command (case-sensitive here; make it case-insensitive if needed) if (strcmp(input, "exit") == 0) { printf("Exiting program via 'exit' command...\n"); keepGoing = false; continue; } // -------------------------- // Insert your program's core logic here // -------------------------- printf("Processing your input: %s\n", input); } while (keepGoing); printf("Program exited successfully!\n"); return 0; }
Key Explanations
strcmp()for string comparisons: This function returns0if the two strings are identical, which is why we checkstrcmp(input, "exit") == 0.- Newline handling:
fgetsreads the newline character when the user presses Enter, so we replace it with a null terminator (\0) to make sure our string comparisons work correctly. - Case insensitivity (optional): Using
tolower()from<ctype.h>lets users press 'Q' instead of just 'q' to exit—remove this if you want case-sensitive behavior. - Safe input with
fgets: Unlikescanf,fgetslimits the number of characters read to the size of your buffer, preventing buffer overflow vulnerabilities.
Quick Fixes for Your Existing Code
If you want to adapt your current code instead of using the full example:
- Replace any
if (exitCon == 'quit')lines withif (strcmp(exitCon, "exit") == 0)(make sureexitConis a char array, not a single char). - For the 'q' check, verify that your input is a single character first, then compare it to 'q' (or 'Q' if you want case insensitivity).
- Always include the necessary headers:
<stdbool.h>forbool,<string.h>for string functions, and<ctype.h>if usingtolower().
内容的提问来源于stack exchange,提问作者Michael Musk
相关产品推荐
相关产品推荐

