%d 占位符输入“3abc”,无法清除 'abc' 缓冲区
%d placeholder input '3abc', cannot clear 'abc' buffer
下面是我的代码:
int length;
char ch;
printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the length of the password: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &num) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the number of passwords you want: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
当我输入的时候abc
okay.
当我输入3abc
时,按长度收到3,但'abc'还在缓冲区中。
我用while ((ch = getchar()) != '\n' && ch != EOF);
清除了还是不行?
感谢专家的任何帮助。
如果 scanf
正确抓取了一个数字作为您的测试用例 3asc
,则您不会刷新 stdin
int length;
int ch;
printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the length of the password: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
// flush stdin
while ((ch = getchar()) != '\n' && ch != EOF);
printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the number of passwords you want: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
并且,已经评论过,要识别ch != EOF
ch
必须int
。此外getchar原型是int getchar(void)
如果scanf()
成功,循环内的内容不会被执行...所以如果你输入“3abc”,scanf()
读取'3'而"abc"是仍在输入缓冲区中,因为您没有进入循环
下面是我的代码:
int length;
char ch;
printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the length of the password: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &num) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the number of passwords you want: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
当我输入的时候abc
okay.
当我输入3abc
时,按长度收到3,但'abc'还在缓冲区中。
我用while ((ch = getchar()) != '\n' && ch != EOF);
清除了还是不行?
感谢专家的任何帮助。
如果 scanf
正确抓取了一个数字作为您的测试用例 3asc
stdin
int length;
int ch;
printf("\n\tEnter the length of the password: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the length of the password: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
// flush stdin
while ((ch = getchar()) != '\n' && ch != EOF);
printf("\n\tEnter the number of passwords you want: ");
while (scanf("%d", &length) != 1) {
printf("\n\tPlease enter digit only.\n");
printf("\n\tEnter the number of passwords you want: ");
while ((ch = getchar()) != '\n' && ch != EOF);
}
并且,已经评论过,要识别ch != EOF
ch
必须int
。此外getchar原型是int getchar(void)
如果scanf()
成功,循环内的内容不会被执行...所以如果你输入“3abc”,scanf()
读取'3'而"abc"是仍在输入缓冲区中,因为您没有进入循环