c++conio

Checking if a char is pressed


The program should read 2 ints and calculate the sum or product depending on the symbol introduced from the keyboard. If you press q at any given momement, it must exit.

#include "stdafx.h"
#include <iostream>
#include<conio.h>

using namespace std;

int main()
{

char k, l ='h',c;     
int a,b,s, p;             

aici: while (l != 'q')
{

    cin >> a;


    if (_kbhit() == 0) //getting out of the loop
    {
        c = a;
        if (c == 'q')
        {
            l = 'q';
            goto aici;
        }
    }


    cin >> b;

    if (_kbhit() == 0)
    {
        c = b;
        if (c == 'q')
        {
            l = 'q';
            goto aici;
        }
    }


    k = _getch();

    if (_kbhit() == 0)
    {
        c = k;
        if (c == 'q')
        {
            l = 'q';
            goto aici;
        }
    }


    if (k == '+')
    {

        s =(int)(a + b);
        cout << s;
    }
    if (k == '*')
    {
        p = (int)(a*b);
        cout << p;
    }
}
return 0;
}

It expects both a and b to be ints so typing 'q' makes a total mess. Is it possible to make the program work without having a and b declared as chars?


Solution

  • You don't need to use goto and kbhit() inside cin. a simple way is:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        int a,b;
        string A, B
        char k;
    
        while(1)
        {
            cin >> A;
            if(A == "q") break;
            cin >> B;
            if(B == "q") break;
    
            a = atoi(A.c_str());
            b = atoi(B.c_str());
    
            cin >> k;
            if(k == 'q') break;
    
            if (k == '+')
                cout << (a + b);
            if (k == '*')
                cout << (a*b);
    
        }
    }