从GNU C库手册:
函数:char * fgets(char * s,int计数,FILE * stream)
fgets函数从流中读取直到换行符(包括换行符)的字符,并将它们存储在字符串s中,并添加一个空字符以标记字符串的结尾。您必须提供计数字符(以s为单位),
但读取的字符数最多为count-1 。多余的字符空间用于在字符串末尾保留空字符。
因此,
fgets(key,1,stdin);读取0个字符并返回。(立即阅读)
使用
getchar或
getline代替。
编辑:
count流中有可用字符时,fgets也不会返回,它会一直等待换行符,然后读取
count字符,因此,在这种情况下,“任何键”可能不是正确的措词。
您可以使用以下示例来避免行缓冲:
#include <stdio.h>#include <termios.h>#include <unistd.h>int mygetch ( void ) { int ch; struct termios oldt, newt; tcgetattr ( STDIN_FILENO, &oldt ); newt = oldt; newt.c_lflag &= ~( ICANON | ECHO ); tcsetattr ( STDIN_FILENO, TCSANOW, &newt ); ch = getchar(); tcsetattr ( STDIN_FILENO, TCSANOW, &oldt ); return ch;}int main(){ printf("Press any key to continue.n"); mygetch(); printf("Bye.n");}


