首页 > 解决方案 > Scanf 函数跳过

问题描述

在类似的问题中,读取字符或字符串的 scanf 会跳过,因为在为前一个 scanf 按下“Enter”键后,它会从输入缓冲区中获取一个新行,但我认为这不是问题所在。如果 input1 是一个整数,这个程序不会跳过第二个 scanf,但是对于其他类型的输入(double、char、string 等)它会跳过它。

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

int main(){
    int input1;
    char input2[6];
    printf("Enter an integer. ");
    scanf("%d", &input1);
    printf("You chose %d\n", input1);
    
    printf("Write the word 'hello' ");
    scanf(" %s", input2);
    
    if (strcmp(input2,"hello")==0){
        printf("You wrote the word hello.\n");
    }  else {
        printf("You did not write the word hello.\n");
    }
    return 0;
}

为什么会这样?

标签: cioscanfuser-input

解决方案


代码中的注释:

int input1 = 0; // Always initialize the var, just in case user enter EOF
                // (CTRL+D on unix) (CTRL + Z on Windows)

while (1) // Loop while invalid input
{
    printf("Enter an integer. ");

    int res = scanf("%d", &input1);
    if ((res == 1) || (res == EOF))
    {
        break; // Correct input or aborted via EOF
    }
    int c;
    // Flush stdin on invalid input
    while ((c = getchar()) != '\n' && c != EOF);
}
printf("You chose %d\n", input1);

另外,看看如何使用 scanf 避免缓冲区溢出


推荐阅读