You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在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

  1. 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 the strcmp() function from <string.h> instead.
  2. 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.
  3. Unprocessed newline characters: If you're using functions like scanf or fgets, 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 returns 0 if the two strings are identical, which is why we check strcmp(input, "exit") == 0.
  • Newline handling: fgets reads 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: Unlike scanf, fgets limits 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 with if (strcmp(exitCon, "exit") == 0) (make sure exitCon is 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> for bool, <string.h> for string functions, and <ctype.h> if using tolower().

内容的提问来源于stack exchange,提问作者Michael Musk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:05:27