getch()和scanf()函数之间的区别

Difference between getch() and scanf() functions

本文关键字:区别 之间 scanf getch 函数      更新时间:2023-10-16

我在执行以下代码时遇到了困难。变量"t"在完成一次执行后取空值。使用getch()而不是scanf()解决了这个问题。但我不知道为什么会这样。有什么解释吗?这是一个不起作用的程序。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
    while(1)
    {
        scanf("%c",&t);
        printf("nValue of t = %c",t);
        printf("nContinue (Y/N):");
        char a=getche();
        if(a=='n' || a=='N')
        exit(0);
   }
}

现在,这就是正确执行的程序。

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
char t;
void main()
{
    while(1)
    {
         t=getch();
         printf("nValue of t = %c",t);
         printf("nContinue (Y/N):");
         char a=getche();
         if(a=='n' || a=='N')
         exit(0);
    }
}

当您读取字符时,

scanf("%c",&t);

输入流中留下了一行换行符,导致后续的scanf()跳过循环中的输入。

注意,getch()是非标准函数。您可以改用getchar()

或者将其更改为:

scanf(" %c",&t); 

请注意格式说明符中的空格,它确保在读取%c的字符之前scanf()跳过所有空白。