C语言解答6位密码输入检测 从键盘输入6位仅由数字0~9组成的密码。用户每输入一个密码并按回车键后,程序给出判断:如果是数字,则原样输出该数字,并提示用户目前已经输入了几位密码,同时继续输入下一位密码;否则,程序提示"error",并让用户继续输入下一位密码。直到用户输入的密码全部是数字为止。 以下为程序的运行结果示例: Input your password: 1↙ 1, you have enter 1-bits number 6↙ 6, you have enter 2-bits number a↙ error d↙ error 4↙ 4, you have enter 3-bits number 6↙ 6, you have enter 4-bits number 8↙ 8, you have enter 5-bits number 2↙ 2, you have enter 6-bits number 输入格式:"%c" 输入提示信息:"Input your password:\n" 如果输入的是数字,输出格式为:"%c, you have enter %d-bits number\n" 如果输入的不是数字,输出提示信息:"error\n"
时间: 2024-02-18 22:02:13 浏览: 122
下面是 C 语言代码实现:
```c
#include <stdio.h>
int main() {
printf("Input your password:\n");
char ch;
int count = 0;
while (count < 6) {
scanf("%c", &ch);
if (ch >= '0' && ch <= '9') {
count++;
printf("%c, you have enter %d-bits number\n", ch, count);
}
else {
printf("error\n");
}
// 清空输入缓冲区
while (getchar() != '\n');
}
return 0;
}
```
注意在读取字符后需要清空输入缓冲区,否则会导致多次循环只读取一次字符。
运行结果示例:
```
Input your password:
1
1, you have enter 1-bits number
6
6, you have enter 2-bits number
a
error
d
error
4
4, you have enter 3-bits number
6
6, you have enter 4-bits number
8
8, you have enter 5-bits number
2
2, you have enter 6-bits number
```
阅读全文