注册 登录
编程论坛 C语言论坛

为什么printf会显示两次

奕奕 发布于 2019-10-31 16:26, 1864 次点击
代码:
#include<stdio.h>
int main()
{
    char user='z',user1;
    int password=123,password1,n=0;
    do
    {
    printf("请输入用户名和密码:");
    scanf("%c,%d",&user1,&password1);
      if(user1=='z'&&password1==123)
      {
        printf("您输入正确,请登录!");
        n=4;
      }
      else
      {
         printf("您输入有误,请重新输入\n");
        n++;
      }
    }
    while(n<4);
    return 0;
}

结果
请输入用户名和密码: p, 123
您输入有误,请重新输入
请输入用户名和密码: p, 123
您输入有误,请重新输入
请输入用户名和密码:您输入有误,请重新输入
请输入用户名和密码: p, 123
您输入有误,请重新输入
Press any key to continue




2 回复
#2
纯蓝之刃2019-10-31 18:11
程序代码:
#include<stdio.h>
int main()
{
    char user='z',user1;
    int password=123,password1,n=0;
    do
    {
    printf("请输入用户名和密码:");
    scanf("%c,%d",&user1,&password1);
      if(user1=='z'&&password1==123)
      {
        printf("您输入正确,请登录!");
        n=4;
      }
      else
      {
        printf("您输入有误,请重新输入\n");
        n++;
      }
      while(getchar()!='\n');
    }
    while(n<4);
    return 0;
}

每次重新输入之前需要使用while(getchar()!='\n');将缓存中的数据全部取出来。
否则如果scanf读取出错的话,未读取的数据还是在缓存里,导致下一次读取后,判断为输入有误。
#3
奕奕2019-10-31 20:02
谢了
1