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

C语言程序遇未知输入触发无限循环问题求助

Fixing Your Infinite Loop & Unreachable Else Block

Hey there, let's break down exactly what's going wrong with your code and get it working as intended:

1. The Fatal Logical Condition Bug

Your else if (cont != 'n' || cont != 'N') line is always true, no matter what character cont holds. Think about it:

  • If you enter x, x != 'n' is true → the whole || expression is true.
  • If you enter n, n != 'N' is true → the expression is still true.

This means every input that isn't y/Y will trigger the "Program Closing" message, and your else block (the invalid input prompt) will never run. That's why you never see the re-entry prompt.

2. Broken Loop Flow & Input Handling

  • Your do-while loop runs first, then checks the condition. But when you get invalid input, you're not updating cont correctly to break the loop or fix the input.
  • The getchar() calls are mispositioned, and scanf("%c") will read leftover newline characters from the input buffer, causing unexpected behavior.

Fixed Code

Here's the corrected version with explanations in comments:

#include <stdio.h>

// Assume this is your existing selection function
void selection() {
    printf("Executing selection logic...\n");
}

int main() {
    char cont;
    printf("Do you want to continue? (y/n)\n");
    // Use " %c" to skip whitespace (like newlines) in the input buffer
    scanf(" %c", &cont);

    do {
        if (cont == 'y' || cont == 'Y') {
            selection();
            // Ask again after running the selection function
            printf("\nDo you want to continue? (y/n)\n");
            scanf(" %c", &cont);
        } else if (cont == 'n' || cont == 'N') {
            printf("Program Closing\n");
            // Let the loop exit naturally since cont matches the while condition
        } else {
            // Catch all invalid inputs here
            printf("Invalid input! Please re-enter (y/n):\n");
            scanf(" %c", &cont);
        }
    } while (cont != 'n' && cont != 'N');

    return 0;
}

Key Changes Made:

  • Fixed the condition logic: We now first check for y/Y, then n/N, and all other inputs fall into the else block (invalid input prompt). No more always-true conditions!
  • Improved input handling: Using scanf(" %c", &cont) (note the space before %c) automatically skips any whitespace characters (like newlines) left in the input buffer, so you won't accidentally read a newline as your input.
  • Adjusted loop flow: After running selection(), we explicitly ask the user again if they want to continue, which makes the program flow intuitive.
  • Removed redundant getchar(): The space in scanf handles whitespace, so we don't need extra getchar() calls anymore.

内容的提问来源于stack exchange,提问作者W Lw

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:48:18