EOF字符
int main(){
int ch = 0;
//ctrl+z
//EOF,实际是文件结束符,也就是-1
while (ch=getchar()!=EOF){
putchar(ch);
}
return 0;
}
输入输出bug
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main(){
int ret = 0;
char password[20] = { 0 };
printf("请输入密码:");
scanf("%s",password);//只读走输入缓冲区的12345,没有读走\n
printf("请确认Y/N");
ret = getchar();//读走\n,直接进入放弃确认
if (ret == 'Y'){
printf("输入成功\n");
}
else{
printf("放弃确认\n");
}
return 0;
}
改进密码输入
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main(){
int ret = 0;
int ch = 0;
char password[20] = { 0 };
printf("请输入密码:");
scanf("%s",password);//只读走输入缓冲区的12345,没有读走\n。如果输入"123456 xyz\n",还是会出问题,scanf只会读取空格前的字符输入缓冲区剩下" xyz\n"
while (ch=getchar()!='\n'){//解决方案:getchar循环读取缓冲区的char字符,知道为\n往下执行
}
printf("请确认Y/N\n");
ret = getchar();//这里才是正常获取用户输入
if (ret == 'Y'){
printf("输入成功\n");
}
else{
printf("放弃确认\n");
}
return 0;
}
只接受数字字符
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main(){
int ch = 0;
while ((ch = getchar() )!= EOF){
if (ch<'0' || ch>'9'){
continue;
}
putchar(ch);
}
return 0;
}