在 scanf 中强制清除缓冲区
forcing the buffer to clear in scanf
我的程序中的 scanf 和输入缓冲区有问题。
首先我要求用户输入:
char someVariable;
printf("Enter text: ");
scanf(" %c",&someVariable);
然后我有一个循环,在 scanf 中一次遍历输入一个字符,直到它到达 \n。
问题是在循环完成后,不知何故,缓冲区中仍然有一些东西,所以这个函数(在循环中被调用)被再次调用并破坏了我程序中的逻辑。
如何强制清除输入缓冲区?
我只能用scanf(赋值要求)
void checkType(){
char userInput;
char tempCheckInput;
printf("Enter Text: ");
scanf(" %c",&userInput);
while (userInput != '\n'){
tempCheckInput = userInput;
scanf("%c",&userInput);
忽略循环结束,那是我得到输入的部分
how can i force clear the input buffer?
在 C 中,stream,如 stdin
,不能像 "delete all input up to this point in time".
那样被清除(以标准方式)
相反,输入可以消耗和抛出(类似于 "cleared")输入直到数据条件。
通常的方式是
int consume_rest_of_line(void) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
;
}
}
如果限于scanf()
int consume_rest_of_line(void) {
char ch;
while (scanf("%c", &ch) == 1 && ch != '\n') {
;
}
}
我的程序中的 scanf 和输入缓冲区有问题。
首先我要求用户输入:
char someVariable;
printf("Enter text: ");
scanf(" %c",&someVariable);
然后我有一个循环,在 scanf 中一次遍历输入一个字符,直到它到达 \n。 问题是在循环完成后,不知何故,缓冲区中仍然有一些东西,所以这个函数(在循环中被调用)被再次调用并破坏了我程序中的逻辑。
如何强制清除输入缓冲区?
我只能用scanf(赋值要求)
void checkType(){
char userInput;
char tempCheckInput;
printf("Enter Text: ");
scanf(" %c",&userInput);
while (userInput != '\n'){
tempCheckInput = userInput;
scanf("%c",&userInput);
忽略循环结束,那是我得到输入的部分
how can i force clear the input buffer?
在 C 中,stream,如 stdin
,不能像 "delete all input up to this point in time".
相反,输入可以消耗和抛出(类似于 "cleared")输入直到数据条件。
通常的方式是
int consume_rest_of_line(void) {
int ch;
while ((ch = getchar()) != '\n' && ch != EOF) {
;
}
}
如果限于scanf()
int consume_rest_of_line(void) {
char ch;
while (scanf("%c", &ch) == 1 && ch != '\n') {
;
}
}