的getch();不会暂停循环

时间:2012-08-21 18:07:33

标签: c getch

我有这段代码:

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

不是在每个循环上等待用户输入,而是在没有我的情况下继续循环;打印

loop
loop
loop

直到我关闭程序。

有没有更好的方法来阅读单个字符?我真正想做的就是让用户输入'y'或'n'

3 个答案:

答案 0 :(得分:3)

只需使用fgetc。我假设您正在使用它来摆脱循环,所以要更新您的示例:

#include <stdio.h>

char iput;

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

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

您也可以使用

fflush(stdin) 

在调用getch之前

问候