scanf 忽略回车键并且不改变变量的值

scanf ignore the enter key and do not change the value of the variable

我正在用C开发一个软件,我需要读取一个整数,但是如果用户按下“enter”键,scanf应该忽略而不是修改变量的当前值。这是一个例子:

#include <stdio.h>
#include <stdlib.h>

void main(void) {

    int a = 5;
    
    printf("\nenter an integer value for the variable 'a': ");
    scanf("%d", &a);
    
    printf("\n the value of variable 'a' is: %d", a);
    //if the user presses the enter key the output is: 5
    
    //if the user enters number 7 the output is: 7
   
}

谢谢

始终检查 scanf 的结果。

你的情况:

if(scanf("%d", &a) != 1)
    printf("\nThe scanf was not successful\nThe value of the `a` was not changed\n");

scanf不成功时,变量不会改变。

https://godbolt.org/z/GcY51W

解决方案:

#include <stdio.h>
#include <stdlib.h>

void main(void) {
    
    int a = 5;
    char number[2]; 
    
    printf("\nenter a value for the variable 'number': ");
    
    fgets(number, 2, stdin); 
    
    if(sscanf(number, "%d")>0){
        a = atoi(number);
    }
    
    printf("variable 'a' is: %d\n", a); 
 
}