如何从标准输入一个字符,而无需等待用户把它? [英] how to get a character from stdin without waiting for user to put it?
本文介绍了如何从标准输入一个字符,而无需等待用户把它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在写打印使用终端的ncurses东西的C程序。它应该停止打印,当用户preSS's'和再继续当preSS的。我怎样才能读取输入的关键,而无需等待用户preSS的关键?
我试过残培()
和的getchar()
,但他们等到的一个关键是pressed。 ..
修改
这是我的code:
INT主要(无效)
{
initscr的(); / *开始诅咒模式* /
刷新(); / *打印它的真实画面* /
INT I = 0,J = 0;
INT状态= 0;
而(1)
{
CBREAK();
INT C =残培(); / *等待用户输入* /
开关(三)
{
案例'Q':
endwin();
返回0;
情况下C:
状态= 1;
打破;
案件的:
状态= 0;
打破;
默认:
状态= 1;
打破;
}
如果(州)
{
移动(I,J);
我++;
J ++;
输出(一);
刷新();
}
}
nocbreak();
返回0;
}
编辑2
这种运作良好。我得到了100分:)
的#include<&stdio.h中GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&curses.h里GT;INT主要(无效)
{
initscr的();
NOECHO();
CBREAK(); //不打断用户输入
超时(500); //等待按键preSS 500毫秒
INT C = 0; //命令:[C | Q | S]
INT S = 1; //状态:1 =打印,0 =不打印;-)
INT I = 0,J = 0;
而(C!='Q')
{
INT C =残培();
开关(三)
{
案例'Q':
endwin();
返回0;
情况下C:
S = 1;
打破;
案件的:
S = 0;
打破;
默认:
打破;
}
如果(多个)
{
移动(I,J);
printw(一);
我++;
J ++;
}
}
endwin();
nocbreak();
返回0;
}
解决方案
Ncurses有着通过它自己的getch()函数来做到这一点的能力。请参见这个页
的#include<&curses.h里GT;诠释主要(无效){
initscr的();
超时(-1);
INT C =残培();
endwin();
的printf(%d个%C \\ n,C,C);
返回0;
}
I'm writing a C program that prints something on terminal using ncurses. It should stop printing when user press 's' and continue again when press 's'. How can I read a key from input without waiting user to press the key?
I tried getch()
and getchar()
but they wait until a key is pressed...
Edit
This is my code:
int main(void)
{
initscr(); /* Start curses mode */
refresh(); /* Print it on to the real screen */
int i = 0, j = 0;
int state = 0;
while (1)
{
cbreak();
int c = getch(); /* Wait for user input */
switch (c)
{
case 'q':
endwin();
return 0;
case 'c':
state = 1;
break;
case 's':
state = 0;
break;
default:
state = 1;
break;
}
if(state)
{
move(i, j);
i++;
j++;
printf("a");
refresh();
}
}
nocbreak();
return 0;
}
EDIT 2 This works well. I got 100 points :)
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main(void)
{
initscr();
noecho();
cbreak(); // don't interrupt for user input
timeout(500); // wait 500ms for key press
int c = 0; // command: [c|q|s]
int s = 1; // state: 1= print, 0= don't print ;-)
int i = 0, j = 0;
while (c != 'q')
{
int c = getch();
switch (c)
{
case 'q':
endwin();
return 0;
case 'c':
s = 1;
break;
case 's':
s = 0;
break;
default:
break;
}
if (s)
{
move(i, j);
printw("a");
i++;
j++;
}
}
endwin();
nocbreak();
return 0;
}
解决方案
ncurses has the capability to do this through it's own getch() function. See this page
#include <curses.h>
int main(void) {
initscr();
timeout(-1);
int c = getch();
endwin();
printf ("%d %c\n", c, c);
return 0;
}
这篇关于如何从标准输入一个字符,而无需等待用户把它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文