我正在编写一个程序,每次调整大小时,它都会用一个字母填充控制台,并且在调整大小时,该字母会更改为字母表中的下一个字母。
我还想在用户按下 q 时程序结束。这目前有效,但是如果我不输入任何字母,那么我的打印代码将永远无法到达。我该如何解决这个问题?
while(1){
keyInput = getch();
if(keyInput == 'q' || keyInput == 'Q'){
break;
}
letter++; //Get next letter
if(letter > 90){
letter = 65; //Loop back to A
}
//Print updated output
pause(); //Wait for sigwinch
clear(); //Clear window
ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws);
resizeterm(ws.ws_row, ws.ws_col);
for(i = 0; i < ws.ws_row; i++){
for(j = 0; j < ws.ws_col; j++){
addch(letter);
}
}
refresh();
}
最佳答案
考虑到调用的组合,OP 正在使用 ncurses(而不是说另一个 conio 问题)。鉴于此(一个完整的程序会有所帮助),以 pause()
开头的 block 是没有意义的,因为如果记得使用 ncurses 将返回 KEY_RESIZE
keypad(stdscr, TRUE);
在初始化部分,以及更新 LINES
和 COLS
值。程序的给定部分可以重写如下:
keypad(stdscr, TRUE); /* allow KEY_RESIZE to be read on SIGWINCH */
timeout(50); /* wait 50 milliseconds for each character */
while(1){
keyInput = getch();
if (keyInput == ERR) {
continue; /* ignore when there was a timeout - no data */
} else if(keyInput == 'q' || keyInput == 'Q'){
break;
} else if (keyInput == KEY_RESIZE) {
letter++; //Get next letter
if(letter > 'Z'){
letter = 'A'; //Loop back to A
}
erase();
move(0,0);
for(i = 0; i < LINES; i++){
for(j = 0; j < COLS; j++){
addch(letter);
}
}
}
}
timeout
调用修复了提到的阻塞问题。
关于c - 在 while 循环中使用 getch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30406064/