JacLax
JacLax

Reputation: 23

Using getch() in while loop

I am writing a program which fills the console with a letter every time it is resized, and when it is resized the letter changes to the next in the alphabet.

I also want to make it so that when the user presses q the program ends. This currently works, however if I do not enter any letter then my printing code is never reached. How do I fix this?

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();
}

Upvotes: 1

Views: 1684

Answers (1)

Thomas Dickey
Thomas Dickey

Reputation: 54583

Given the combination of calls, the OP is using ncurses (rather than say, yet another conio question). Given that (a complete program would help), the chunk beginning pause() is meaningless, since ncurses will return KEY_RESIZE if one remembers to use

keypad(stdscr, TRUE);

in the initialization section, as well as updating the LINES and COLS values. The given section of the program could be rewritten something like this:

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);
        }
      }
    }
}

The timeout call fixes the blocking-problem alluded to.

Upvotes: 1

Related Questions