c++ - Checking if a char is pressed -
the program should read 2 ints , calculate sum or product depending on symbol introduced keyboard. if press q @ given momement, 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 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 , b ints typing 'q' makes total mess. possible make program work without having , b declared chars?
you don't need use goto , kbhit() inside cin. simpel 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; = 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); } }
Comments
Post a Comment