getch(); does not pause the loop

喜你入骨 提交于 2019-12-11 09:41:24

问题


I have this piece of code for instance:

while(true){
    printf("looping");
    getch();
}

Instead of waiting for user input on each loop, the loop just continues without me; printing

loop
loop
loop

until I close the program.

Is there a better way to read a single character ? All i really want to do is to have the user input a 'y' or a 'n'


回答1:


Just use fgetc. I assume you're using this to break out of the loop, so to update your example:

#include <stdio.h>

char iput;

while(true){
    printf("looping");
    iput = fgetc(stdin);
    if(iput == 'n')
      break;
} 



回答2:


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
   while(1)
 {
   printf("\nlooping");
   char t=getch();
   if(t=='n')
   exit(0);
 }
}



回答3:


You can also use

fflush(stdin) 

before calling getch

regards



来源:https://stackoverflow.com/questions/12060572/getch-does-not-pause-the-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!