2016-11-10 17 views
0

プログラムは2つの整数を読み、キーボードから導入された記号に応じて合計または積を計算する必要があります。任意の瞬間にqを押すと、それは終了する必要があります。charが押されているかどうかの確認

#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をcharとして宣言せずにプログラムを動作させることはできますか?

+0

スタートの線に沿って何かを行うことが可能です。簡単な使用シナリオ、**ユースケース**を記述してください。 –

+1

'kbhit'と' cin'を混ぜるのは悪い考えです。 'cin'が戻るのを待っている間にブロックされている間は、' kbhit'のテストはできません。 – user4581301

+1

オフトピック:これらの '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 >>'はenterを押すまで戻りません。つまり、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.

関連する問題