【发布时间】:2017-05-25 11:53:42
【问题描述】:
下面是我的代码:
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 好的时候。
当我输入3abc时,按长度收到3,但'abc'仍在缓冲区中。
我用while ((ch = getchar()) != '\n' && ch != EOF);清除了还是不行?
感谢专家的任何帮助。
【问题讨论】:
-
您是否将
ch声明为int? -
char ch; -
识别
ch != EOFch必须是int... -
getchar 返回 int 类型。见原型:
int getchar(void) -
或者注释不是指你要问的问题,而是你代码的问题之一。