加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

如何通过从键盘获取任何值来打破Linux上的C循环?

发布时间:2020-12-14 01:04:23 所属栏目:Linux 来源:网络整理
导读:我正在构建的程序在无限循环中运行,其中包含一个开关盒.我想在每种情况下插入一个while循环并在循环中执行一些操作,但是一旦给出键盘输入,循环就应该退出.因此,在从键盘获取输入之后,另一个案例在其中嵌套了while循环,并且该过程继续. 结构是: while()//inf
我正在构建的程序在无限循环中运行,其中包含一个开关盒.我想在每种情况下插入一个while循环并在循环中执行一些操作,但是一旦给出键盘输入,循环就应该退出.因此,在从键盘获取输入之后,另一个案例在其中嵌套了while循环,并且该过程继续.

结构是:

while()//infinite loop
    {
    ...............      //operations
    ...............      //operations
    switch()
        {
        case 1:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;

        case 2:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;


        case n:
        ...............    //operations
        ...............    //operations
        while()//infinite loop
             {
             ..............
             ..............
             exit if there is any input from keyboard
             }
        break;
        }
  }

有什么办法吗???

解决方法

Linux键盘输入是缓冲的,为了捕获动态命中的密钥,您必须配置TERM IO.

在main()顶部附近添加一个调用(参见下面的代码)

term_nonblocking();

读取即时按下的键,而不等待回车(CR).

码:

struct termios stdin_orig;  // Structure to save parameters

void term_reset() {
        tcsetattr(STDIN_FILENO,TCSANOW,&stdin_orig);
        tcsetattr(STDIN_FILENO,TCSAFLUSH,&stdin_orig);
}

void term_nonblocking() {
        struct termios newt;
        tcgetattr(STDIN_FILENO,&stdin_orig);
        fcntl(STDIN_FILENO,F_SETFL,O_NONBLOCK); // non-blocking
        newt = stdin_orig;
        newt.c_lflag &= ~(ICANON | ECHO);
        tcsetattr(STDIN_FILENO,&newt);

        atexit(term_reset);
}

注意:当程序退出时,将自动调用term_reset()(重置终端参数).

您可以在程序中的任何位置调用现在非阻塞的getchar()来检测按键

int i = getchar();

并检查是否按下了某个键:

if (i > 0) {
    // key was pressed,code in `i`
}

在您的程序中,例如:

int key = 0;

while (... && key <= 0) {
   // ... 
   key = getchar();
}

注意:如果您希望输出无缓冲,请调用setbuf(stdout,NULL);

(来自@stacey的注释:当没有密钥可用时,getchar()可能返回0或-1)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读