I am learning to programm in C++, for now with the nucrses library. I have a small problem that has taken me a full day so far without reaching a solution. Would be very grateful if someone could help...heres my issue:
I am combining a getch() function with a switch() function. When the getch() is part of the int main(), no problem.
When getch is included in a function, which is called just before the switch() function, its not working. I need to have the getch() in a function just to reduce the number of lines in my code.
#include <stdlib.h>
#include <ctype.h>
#include <curses.h>
void getch_function(int answer);
int main () {
int answer;
initscr ();
//answer=getch(); //<-- works ok when this is active instead of the line below
getch_function(answer); //<-- doesn't work when calling getch() from a custom function
switch (answer) {
case'1':
printw(" TEXT1");
break;
case'2':
printw(" TEXT1");
break;
case'3':
printw(" TEXT1");
break;
}
getch();
endwin ();
return 0;
}
void getch_function(int answer){
answer=getch();
}
I know it is possible to call the getch() function from a custom function because I managed to do it in the past, but now I cant do that anymore...
There's no problem with calling getch. The problem is that 'answer' in getch_function() is a copy of 'answer' in main(). Therefore any changes made to 'answer' in getch_function() have no effect on 'answer' in main().
Use a reference instead. (void getch_function(int& answer){...})