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

C语言中Do while循环结合switch case无法正常运行的问题排查

Let's walk through what's going wrong with your code—there are a few key issues here that are keeping your switch branches from firing, plus some input handling quirks to straighten out.

1. The Big Problem: Character vs. Integer Constants

Your switch statement uses case '3' and case '0', but your variable I is an integer (int), and you're reading it with scanf_s("%d", &I)—which reads numeric integer values, not character ASCII codes.

The character '3' has an ASCII value of 51, and '0' is 48. When you type the number 3 or 0, scanf_s stores the integer 3 or 0 in I—so these will never match the character constants in your case labels. That's why your switch branches never trigger!

Fix: Replace the character constants with integer constants:

case 3:
case 0:
2. Messy Input Handling

Even after fixing the switch, your input logic has some bugs that will confuse users or cause unexpected behavior:

  • Redundant getchar() calls: You call getchar() right after scanf_s, which eats the newline left in the input buffer—but then you add another getchar() inside the case 3 branch. This makes the program wait for an extra keypress that users won't expect. Instead, use a helper function to clear the input buffer consistently.
  • Broken default branch logic:
    • The condition if (scanf_s("%d", &I) != 3 || scanf_s("%d", &I) != 0) makes no sense. scanf_s returns the number of successfully read values (here, 1 if it reads an integer, 0/EOF if not)—it will never return 3 or 0. This condition will always be true, and calling scanf_s twice forces users to input twice, which isn't what you want.
    • fflush(stdin) is undefined behavior in C. The standard only allows fflush on output streams. To clear the input buffer, read all remaining characters until you hit a newline or EOF.
  • Readability issue: The while (I != 0); line is separated from the do block's closing brace. It works, but grouping them together makes the code easier to follow.
3. Fixed Code Example

Here's a cleaned-up version of your code that addresses all these issues:

#include <stdio.h>

// Helper function to clear leftover characters in the input buffer
void clear_input_buffer() {
    int c;
    while ((c = getchar()) != '\n' && c != EOF);
}

int main() {
    int I = 1;
    printf("Press enter to start the loop...");
    getchar(); // Wait for user to press enter

    do {
        printf("\nYou are in a LOOP. Would you like to stay in it, or leave it? \nPress 0 to leave the loop or press 3 to stay in it: ");
        
        // Handle invalid input (non-numeric values)
        if (scanf_s("%d", &I) != 1) {
            printf("\nInvalid input! Please enter a number.\n");
            clear_input_buffer();
            continue;
        }
        clear_input_buffer(); // Clear the newline after the integer input

        switch (I) {
            case 3:
                printf("\nYou are STILL inside the LOOP. Next time press 0 to exit.\n");
                break;
            case 0:
                printf("\nExiting the LOOP...");
                break;
            default:
                printf("\nPlease, enter a valid command (0 to exit, 3 to stay): ");
                break;
        }
    } while (I != 0);

    printf("\nCongratulations! You are OUT of the LOOP!");
    return 0;
}
Key Takeaways
  • Always match your case constant types to your switch variable type: integers use integer constants, chars use character constants.
  • Be careful with input buffers—avoid redundant reads and never use fflush(stdin).
  • Encapsulate repetitive logic (like clearing the input buffer) into helper functions to keep your code clean.

内容的提问来源于stack exchange,提问作者Azu Serra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:49:24