C++ and Keypressed

Hello I'm trying to create something but instead of the usual cin where the user has to press enter, I want to see how it can be done without pressing enter but just by pressing a key?

I'm not sure how to do this I think I got a base but it might not be correct, I searched online but I couldn't really find the right solution.


Basically in this program I want if the user presses 1 to ask him for numbers and then get their added value, and if the user presses 2 to ask him for numbers and then get their divided value.

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
35
36
37
38
39
40
41
#include <iostream>
#include <conio.h>

using namespace std;

int add(int x, int y) {
        return x+y;
}
int substract(int x, int y) {
        return x-y;
}
int getch(void);



int main()
{
    int x, y;
    int c;
    
    cout <<"Please choose:"<<endl;
    cout<<"1.For adding press 1"<<endl;
    cout<<"2.For substracting press 2"<< endl;
    cout<<"3.For multiplication press 3"<<endl;
    cout<<"4.For dividing press 4" <<endl;
    c = getch();


    if(c=1){
        cout<<"Please enter a value for x and y" <<endl;
        cin>>x>>y;
        add(x,y);
    }
    else if(c=2){
        cout<<substract(x,y);
    }
    return 0;
}





Thanks
You may try the switch statement, and read up on it. It is perfectly suited for what you are trying to accomplish without being verbose.

1
2
3
4
5
6
7
8
9
10
11
12
13
std::cin >> input;
std::cin >> x >> y;

switch ( input )
{
  case 1: add(x,y);
  break;
  case 2: subtract(x,y);
  break;
  //etc...
  default: std::cout << "You didn't enter a valid number." << std::endl;
}


yes, I know about switch and it's great for this but what I want to learn is how to do an action when a key is pressed.
Ok so I tried with switch

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
35
36
37
38
39
#include <iostream>
#include <conio.h>

using namespace std;
int getch(void);
int add(int x, int y) {
    int z;
    z=x+y;
    return z;
};
int subtract(int x, int y) {
        return x-y;
        cout<<"Answer is "<<x-y;
};
int main()
{
    int a, b, c;


    cout<<"Enter 2 numbers"<<endl;
    cin>>a>>b;


    cout <<"Please choose:"<<endl;
    cout<<"1.For adding press 1"<<endl;
    cout<<"2.For substracting press 2"<< endl;
    cout<<"3.For multiplication press 3"<<endl;
    cout<<"4.For dividing press 4" <<endl;
    c=getch();
switch (c)
{
  case 1: add(a,b);
  break;
  case 2: subtract(a,b);
  break;
  default: cout << "You didn't enter a valid number." << endl;
}
    return 0;
}

but whenever I press 1 or 2 it reads the default message.
How do I let the computer know that case 1 = the 1 KEY
Last edited on
Try this:

1
2
3

switch( atoi( c ) )
or use case '1': etc which will switch off the ascii value of the key pressed
Last edited on
Yep Texan40, that would work as well!
Topic archived. No new replies allowed.