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

C语言练习:用fgets拒绝换行符输入,解决程序挂起问题

How to Reject Empty Newline Input with fgets

Absolutely, this is a common gotcha when working with fgets—but we can fix it with some simple input validation right after reading. Here's how to handle it cleanly, while also making your program more robust against other edge cases:

Core Idea

When a user hits Enter without typing anything, fgets will read that single newline character (\n) plus the null terminator into your buffer. We just need to check for this case and prompt the user to try again until they provide valid, non-empty input.

Example Code

#include <stdio.h>
#include <string.h>

int main() {
    char input_buffer[256];
    int is_valid = 0;

    while (!is_valid) {
        printf("Enter your input: ");
        
        // Read input with fgets
        if (fgets(input_buffer, sizeof(input_buffer), stdin) == NULL) {
            fprintf(stderr, "Error reading input or EOF detected.\n");
            return 1;
        }

        // Check if user only pressed Enter (input starts with newline)
        if (input_buffer[0] == '\n') {
            printf("Oops! Empty input isn't allowed. Please enter something and try again.\n");
            continue;
        }

        // Remove the trailing newline from valid input (optional but useful)
        input_buffer[strcspn(input_buffer, "\n")] = '\0';

        // Handle cases where input was longer than the buffer (clear leftover characters)
        if (strlen(input_buffer) == sizeof(input_buffer) - 1 && input_buffer[sizeof(input_buffer)-2] != '\n') {
            printf("Heads up: Your input was too long—we truncated the extra characters.\n");
            // Clear the rest of the input buffer to avoid messing up future reads
            int leftover_char;
            while ((leftover_char = getchar()) != '\n' && leftover_char != EOF);
        }

        is_valid = 1;
        printf("Great! You entered: %s\n", input_buffer);
    }

    return 0;
}

Key Details to Note

  • Rejecting empty newlines: The check input_buffer[0] == '\n' catches the case where the user just hits Enter. We use a continue to loop back and ask for input again.
  • Trimming the newline: strcspn finds the position of the first newline, so replacing that with a null terminator cleans up the input for later use.
  • Clearing excess input: If the user types more characters than your buffer can hold, fgets will truncate the input, leaving the rest in the stdin buffer. The getchar() loop clears these leftovers so they don't interfere with future input reads.
  • Avoid fflush(stdin): This is undefined behavior in standard C, so it's better to use the getchar() approach to clear the buffer portably.

Bonus Robustness Tip

Always check if fgets returns NULL—this can happen if there's an input error or the user sends an EOF (like Ctrl+D on Unix or Ctrl+Z on Windows). Handling this prevents your program from crashing or behaving unpredictably.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:29:17