【问题标题】:How to use scanf after Wrong input format (the garbage value)?输入格式错误(垃圾值)后如何使用scanf?
【发布时间】:2021-08-24 07:09:24
【问题描述】:

我正在尝试一一获取两个整数输入。但是,当我在第一个输入中使用了错误的输入格式(如 char/string/floating-point)时,程序结束时没有得到第二个输入。

虽然有一些方法可以解决这个问题,比如使用带有字符输入的 isdigit(),但我想使用 scanf_s 和 "%d" 来解决这个问题。

#include <stdio.h>

int main() {

    unsigned int id = 0;

    printf("Enter ID\n");
    scanf_s("%d", &id);

    printf("%d\n", id);

    unsigned int id2 = 0;

    printf("Enter ID2\n");
    scanf_s("%d", &id2);

    printf("%d\n", id2);

    return 0;
}

【问题讨论】:

  • 测试scanf_s的返回值是否成功,并做正确的动作(再次询问或继续)。

标签: c integer printf scanf garbage


【解决方案1】:

scanfscanf_s 返回成功分配的字段数。所以简单地使用:

if(scanf_s("%d", &id) != 1) {
    // Handle error
}

你可以这样做:

int r;
do {
    printf("Enter ID\n");
    r = scanf_s("%d", &id);
} while(r!=1)

【讨论】: