日期:2014-05-16  浏览次数:21064 次

怎么在Linux下C语言中才能实现:按任意键继续的功能
原先写一个程序时候感觉实现这部分的功能也是蛮简单的,心想用{printf("按任意键退出\n");getch();}就可以搞定了,但是发现就是实现不了这部分的功能,总是一闪而过。头文件#include <curses.h>都加了,编译选项都加上了 -lcurses,发现效果一样,还是不能起到按任意键继续,很郁闷。请教各位大虾们伸手救援!心存感谢!

------解决方案--------------------
/***********************************************
 function:接收一个字符立即生效(不打印)
返回字符的ascii码
 ***********************************************/
int getch() //windows下可以直接用这个函数但要加头文件conio.h
{
struct termios tm, tm_old;
int fd = STDIN_FILENO,c;

if (tcgetattr(fd, &tm) < 0)
{
return -1;
}

tm_old = tm;
cfmakeraw(&tm);

if (tcsetattr(fd, TCSANOW, &tm) < 0)
{
return -1;
}

c = fgetc(stdin);

if (tcsetattr(fd,TCSANOW,&tm_old) < 0)
{
return -1;
}

return c;
}
------解决方案--------------------
看看行不行?

#include <stdio.h>
#include <stdlib.h>

int main() {
int c;

printf("按任意键退出\n");
system("stty raw -echo");
c = getchar();
system("stty cooked echo");

return 0;
}

------解决方案--------------------
C/C++ code

#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>

int getch();

void press_key();

int main()
{
   printf("Hello world!\n");
   press_key();
   return 0;
}

void press_key()
{
   printf("Press any key to continue...\n");
   getch();
}

int getch()
{
   struct termios tm, tm_old;
   int fd = STDIN_FILENO,c;

   if (tcgetattr(fd, &tm) < 0)
   {
      return -1;
   }

   tm_old = tm;
   cfmakeraw(&tm);

   if (tcsetattr(fd, TCSANOW, &tm) < 0)
   {
      return -1;
   }

   c = fgetc(stdin);

   if (tcsetattr(fd,TCSANOW,&tm_old) < 0)
   {
      return -1;
   }

   return c;
}