问题描述
我需要用C语言编写一个程序,该程序将执行以下操作:例如,当我按下"a"时,终端将在无休止的循环中输入该键入的字符,如下所示:aaaaaaaaaaaaaaaaaa ...直到另一个键,例如将按下"b".最终输出应如下所示:aaaaaaaaabbbbbbq(q应终止程序).我的代码在这里:
I need to write a program in C language which will be doing something like this:For example, when I will press "a", terminal will be writing that typed character in the unending loop like this: aaaaaaaaaaaaaaaa...until another key, for example "b" will be pressed. Final output should look like this: aaaaaaaaabbbbbbq (q should terminate the program).My code here:
int main(int argc, char** argv) {
int c;
static struct termios staryTermios, novyTermios;
tcgetattr(STDIN_FILENO, &staryTermios);
novyTermios = staryTermios;
novyTermios.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &novyTermios);
while ((c = getchar()) != 'q') {
putchar(c);
}
tcsetattr( STDIN_FILENO, TCSANOW, &staryTermios);
return 0;
}
此版本只输入一次键入的字符,然后等待再次按键
this version writes the typed characters only once and then it waits for another keypress
推荐答案
我想您将需要两个线程,这两个线程都将访问一个公共变量.一个线程的工作是连续打印公共变量.第二个任务是等待键盘输入并相应地更新变量.
I guess you will need two threads which will both be accessing a common variable. The job of one thread would be to continuously print the common variable. The job of the second would be to wait for input from the keyboard and update the variable accordingly.
这篇关于在Linux C中用按键打破循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!