I try to make a menu with ncurses library, I made a switch with a getch() that takes the input. When I'm moving in the menu I need to press twice the keys to get the right input. For example if I want to go to the "exit" line from "options" line I need to press twice the KEY_DOWN, if I press only one time the cursor doesn't move. This is the code:
#include <iostream>
#include <cstring>
#include <ncurses.h>
void start(){
initscr();
noecho();
raw();
cbreak();
}
void position(WINDOW* win, int curr, char string1[], char string2[], char string3[]){
if(curr==1){
mvwaddstr(win, 7, 21, string2);
mvwaddstr(win, 8, 21, string3);
wattron(win, A_REVERSE);
mvwaddstr(win, 6, 21, string1);
wrefresh(win);
}
else if(curr==2){
mvwaddstr(win, 6, 21, string1);
mvwaddstr(win, 8, 21, string3);
wattron(win, A_REVERSE);
mvwaddstr(win, 7, 21, string2);
wrefresh(win);
}
else{
mvwaddstr(win, 6, 21, string1);
mvwaddstr(win, 7, 21, string2);
wattron(win, A_REVERSE);
mvwaddstr(win, 8, 21, string3);
wrefresh(win);
}
wattroff(win, A_REVERSE);
}
int main (){
start();
WINDOW * win = newwin (20, 50, 0, 0);
refresh();
box (win, 0, 0);
wrefresh(win);
keypad(win, TRUE);
int length = 20, current = 1;
char string1[length], string2[length], string3[length];
strncpy(string1, "NEW GAME", 10);
strncpy(string2, "OPTIONS", 10);
strncpy(string3, "EXIT", 10);
mvwaddstr(win, 7, 21, string2);
mvwaddstr(win, 8, 21, string3);
mvwaddstr(win, 6, 21, string1);
wrefresh(win);
while(getch()!='x'){
int push = wgetch(win);
switch(push){
case KEY_UP:
current--;
if(current==0){
current=1;
}
break;
case KEY_DOWN:
current ;
if(current==4){
current=3;
}
break;
case 10:
break;
default:
break;
}
position(win, current, string1, string2, string3);
}
getch();
endwin();
return 0;
}
CodePudding user response:
You call (w)getch
twice in the loop:
while(getch()!='x'){
int push = wgetch(win);
// ...
}
Try this to get the character and check for the loop condition at the same time:
int push;
while ((push = wgetch(win)) != 'x'){
// ...
}