我在程序中有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);
忽略循环的结尾,这就是我得到输入的部分
如何强制清除输入缓冲区?
在C中,无法清除流(如)stdin
(以标准方式),如“删除到该时间点的所有输入”一样。
取而代之的是,输入可以消耗并折腾(类似于“清除”)输入,直到达到数据条件为止。
通常的方法是
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') {
;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句