getch() inside a function

Hi all,

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.

Here below my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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...

Anyone can help ?

thx

Wissam
Last edited on
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){...})
Thank you very much hamsterman,

works perfectly now.

Have a very good day.
Topic archived. No new replies allowed.