2017-03-12 24 views
1

私のプログラムはユーザーデータをtupleとして受け取り、vectorに格納します。 tupleを何個追加できるかには制限がなく、tupleを追加するとvectorサイズが変更されます。プログラムは、ユーザーに別のものを追加するかどうかを尋ねますtuple。いいえの場合、ループは終了します。C++ 11:cinはユーザー入力を待たずにループを終了します

私の問題は、プログラムが「はい」または「いいえ」入力を待つと思われるとき、cinをスキップしてループを終了したことです。

解決策を探してみましたが、バッファをクリアしようとしましたが、正方形に戻りました。ここ

#include <iostream> 
#include <string> 
#include <tuple> 
#include <vector> 
using namespace std; 

void print(vector<tuple<int, string, string, bool>> const & data) 
{ 
    if (data.size() != 0) 
    { 
     for (auto row : data) 
     { 
      cout << get<0>(row) << ", " << get<1>(row) << ", " << get<2>(row) 
       << ", " << get<3>(row) << endl; 
     } 
    } 
    else 
    { 
     cout << "\nNO ENTRIES CURRENTLY!"; 
    } 
} 
int main() 
{ 
    int id; 
    char go; 
    string name, filePath; 
    bool flag = false; 
    typedef tuple<int, string, string, bool> pData; 
    vector<pData> pList; 

    do 
    { 
     cout << "Enter a Pattern Call:" << endl; 
     cin >> id >> name >> filePath >> flag; 

     pList.push_back(make_tuple(id, name, filePath, flag)); 

     cout << "Do You wish to add another: "; 
     cin.ignore(); 
     cin >> go; //The control skips here and exits the loop. 
    } while (go == 'y' || go == 'Y'); 

    print(pList); 

    return 0; 
} 
+0

あなたの最善の策は、ライン - 読むことです'getline'を使って行ごとに並べ替えます。 –

答えて

0

ルック: How do I flush the cin buffer? ユーザ入力は、我々が望むものを正確でない場合は、CINを使用することは容易または安全ではありません。

1

私はLinuxマシンで動作するように見えるハックを持っています。あなたのコードのcin.ignore(1)

パートでcin.ignore()を交換しcin.clear()

  • cin.ignore()

    1. 以下のようになります追加:

      cout << "Do You wish to add another: "; 
          cin.clear(); 
          cin.ignore(1); 
          cin >> go; //The control skips here and exits the loop. 
      
  • +0

    あなたの解決策を試しました。問題はまだ続きます。 –

    関連する問題