Scanf 函数跳过

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

#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;
}

为什么会发生这种情况?

zhang20090630 回答:Scanf 函数跳过

代码中的注释:

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);

另外,看看How to avoid buffer overflow using scanf

,

您是否尝试在 %c 或 %s 或 %d 之后写入“%*c”? 像这样: scanf("%s%*c",input1);

本文链接:https://www.f2er.com/27137.html

大家都在问