C语言练习:用fgets拒绝换行符输入,解决程序挂起问题
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 acontinueto loop back and ask for input again. - Trimming the newline:
strcspnfinds 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,
fgetswill truncate the input, leaving the rest in the stdin buffer. Thegetchar()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 thegetchar()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

