scanf输入验证问题:输入含多值时如何终止程序
The issue you're seeing happens because scanf("%d", &x) only reads the first integer from the input buffer—any remaining characters (like the second 1 in your example) stay in the buffer and get picked up by the next scanf call automatically. To fix this while sticking to scanf, we need to validate that after entering each number, there are no extra non-whitespace characters on the same line.
Here's the modified code that implements this check:
#include <stdio.h> #include <ctype.h> // For isspace() int main() { int x, y; char c; printf("enter a number: \n"); if (scanf("%d", &x) != 1) { // Failed to read integer return 1; } // Check for extra characters on the line while (scanf("%c", &c) == 1) { if (c == '\n') { // End of line, input is valid break; } if (!isspace(c)) { // Non-whitespace character found—invalid input fprintf(stderr, "Error: Extra characters detected after the number.\n"); return 1; } } printf("enter another number: \n"); if (scanf("%d", &y) != 1) { return 1; } // Repeat the check for the second number while (scanf("%c", &c) == 1) { if (c == '\n') { break; } if (!isspace(c)) { fprintf(stderr, "Error: Extra characters detected after the number.\n"); return 1; } } // Your "do some stuff" code here printf("x = %d, y = %d\n", x, y); return 0; }
How This Works:
- Reading the Integer: We first use
scanf("%d", &x)to read the integer as before. - Validating the Rest of the Line: After reading the integer, we loop through each remaining character in the input buffer:
- If we hit a newline (
\n), that means the line only contained the integer (and optional whitespace), so we proceed. - If we encounter any non-whitespace character (like the second
1in your example), we print an error and terminate the program immediately. - Whitespace characters (spaces, tabs) are skipped since they're harmless, but we keep checking until we reach the newline.
- If we hit a newline (
This ensures that each input line contains exactly one integer (with optional leading/trailing whitespace) and no extra content. If a user enters 1 1 for the first number, the loop will detect the second 1 as a non-whitespace character and exit the program before reading y.
内容的提问来源于stack exchange,提问作者Liran ben david

