首页 > 解决方案 > 是否可以对同一个变量使用 scanf 两次?

问题描述

是否可以提示用户再次输入一个字符并让新字符替换原来的字符?当我尝试这个时,它不允许我第二次输入字符。

#include <stdio.h>

int main(){ 
    char x;

    printf("enter value: ");
    scanf("%c", &x);
    
    printf("enter value: ");
    scanf("%c", &x);
}

标签: c

解决方案


#include<stdio.h>
int main(){ 
    char x='p';

    printf("enter value: ");
    scanf("%c", &x);
    printf("val is %c \n",x);
    printf("enter 2nd value: ");
    getchar();//flush the buffer
    scanf("%c", &x);
    printf("val is %c \n",x);
}

问题是您没有清除缓冲区 getchar 函数将清除它。


推荐阅读