getchar相关的,清除缓存不懂

嘎炜 2023-05-17 22:51:06
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	char password[20] = { 0 };
	printf("请输入密码:>");
	scanf("%s",password);
	int ch = 0;
	while ((ch = getchar()) != '\n')
	{
		;
	}
	printf("请确认密码(Y\N):>");
	int ret = getchar();

	if ('Y' == ret)
		printf("Yes\n");
	else
		printf("No\n");
}

里面int ch = 0 ;

while((ch = getchar()) != ' \n')

{

        ;

}可以清除缓存啊,真看不懂里面那个空语句。

...全文
89 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2023-05-18
精选
  • 打赏
  • 举报
回复

printf一个不以\n结尾的字符串,要想确保字符串真正显示出来,别缓存在标准输出缓冲区中,需要紧跟一句fflush(stdout);
rewind(stdin);//这才是C清标准输入缓存的正确方式
cin.clear();cin.sync();//这才是C++清标准输入缓存的正确方式

赵4老师 2023-05-18
  • 打赏
  • 举报
回复

输入密码参考下面:

#include <conio.h>
#include <stdio.h>
char pw[40];
int i,ch;
FILE *f;
void main() {
    cprintf("\r\nPassword:");
    i=0;pw[i]=0;
    while (1) {
        ch=getch();
        if (ch==13 || i>=39) break;
        switch (ch) {
        case 27:
            cprintf("\rPassword: %40s"," ");
            cprintf("\rPassword: ");
            i=0;pw[i]=0;
            break;
        case 8:
            if (i>0) {
                i--;
                pw[i]=0;
                cprintf("\b \b");
            }
            break;
        default:
            pw[i]=ch;
            i++;
            pw[i]=0;
            cprintf("*");
            break;
        }
    }
    cprintf("\r\n");
    f=fopen("password.txt","w");
    fprintf(f,"%s\n",pw);
    fclose(f);
}


CSDN-Ada助手 2023-05-17
  • 打赏
  • 举报
回复
您的问题已经帮您同步至问答, 链接: https://ask.csdn.net/questions/7946772, 请您保持关注, 如果回答有帮助解决此问题, 麻烦您动动小手给相关的回答点赞, Ada会在评论区为您更新结题状态

69,512

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧