2016-11-10 7 views
0

프로그램은 2 정수를 읽고 키보드에서 도입 된 기호에 따라 합계 또는 곱을 계산해야합니다. 특정 순간에 q를 누르면 종료해야합니다.문자가 눌려 졌는지 확인

#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; 
} 

'a'와 'b'는 모두 int이므로 'q'를 입력하면 전체가 엉망이됩니다. a 및 b를 문자로 선언하지 않고 프로그램을 작동시킬 수 있습니까?

+0

시작의 라인을 따라 뭔가를 할 수있는 가능성이있다. 간단한 사용 시나리오 ** 유스 케이스 **를 작성하십시오. –

+1

'kbhit'와'cin'을 섞는 것은 나쁜 생각입니다. 'cin'이 돌아 오기를 기다리는 동안 차단되었지만'kbhit'에 대해서 테스트 할 수는 없습니다 – user4581301

+1

Off 주제 : 모든'goto'는'continue'로 대체 될 수 있습니다. 그렇게 적은 사람들에게 불쾌감을 줄 것입니다. – user4581301

답변

0

cin에는 goto 및 kbhit()를 사용할 필요가 없습니다. simpel 방법입니다 :이 경로에 있어야 할 위치는 얻을 수없는

#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); 

    } 
} 
+0

문제가 잘 풀리지 만,'cin >>'은 엔터를 누를 때까지 돌아 가지 않습니다. 즉, q를 치면 즉시 종료되지 않습니다. 이 작업을하려면 표준 라이브러리 외부로 가야합니다. – user4581301

0

. 표준 입력 스트림 읽기가 차단되어 'q'를 찾고 종료하지 못합니다.

대신 'q'에 대한 모든 입력을 살펴보고 완전한 메시지가 나온 후에 나중에 필요한 값으로 변환하십시오. 같은 뭔가 :

while (int input = _getch()) != 'q') // if read character not q 
{ 
    accumulate input into tokens 
    if enough complete tokens 
     convert numeric tokens into number with std::stoi or similar 
     perform operation 
     print output 
} 

그것은 당신이 사용자의 관점에서 작업하는 방법에 대해 생각으로

std::stringstream accumulator; 
while (int input = _getch()) != 'q') // if read character not q 
{ 
    accumulator << std::static_cast<char>(input); 
    if (got enough complete tokens)// this be the hard part 
    { 
     int a; 
     int b; 
     char op; 
     if (accumulator >> a >> b >> op) 
     { // read correct data 
      perform operation op on a and b 
      print output 
     } 
     accumulator.clear(); // clear any error conditions 
     accumulator.str(std::string()); // empty the accumulator 
    } 
} 

std::stringstream documentation.