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

scanf输入验证问题:输入含多值时如何终止程序

Solution to Prevent Extra Input from Being Reused

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:

  1. Reading the Integer: We first use scanf("%d", &x) to read the integer as before.
  2. 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 1 in 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.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:41:55