0

これが私が書いたコードです。ご覧のとおり、単純なテンプレートの PRINT 関数があります。実際には INT 型のベクトルでは機能しますが、DOUBLE では機能しません。何が問題なのですか?

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

 template <typename T>
 void print (vector<T> &v) {
     for (int i=0; i<v.size(); i++)
         cout<<v[i]<<'\t'; 
 }

 int main() {
    vector<int> vec;
    int a;
    while (cin>>a)
       vec.push_back(a);
    print(vec);
    vector<double> vec1;
    double b;
    while (cin>>b)
       vec1.push_back(b);
   print(vec1);
   return 0;
   system("pause");
}

while (some_integer<10) のように、定義された while サイクルでテストしましたが、動作しますが、実行する回数の値が定義されていないと動作しません。それを理解できませんでした

4

1 に答える 1

4

効果的なループは次のとおりです。

// Continue reading things while cin is in a good state and the read succeeds (int datatype)
while (cin >> a) // ...

そのループを終了するには、整数以外のもの (文字や . など) を読み取り、cin は失敗状態になります。

失敗状態にある間、その後のすべての読み取りはサイレントに失敗します。

cin.clear()それ以降のものを読み取ろうとする前に、失敗状態をクリアする必要があります!

于 2013-05-14T20:05:49.467 に答える