关于输入数据

About input data

本文关键字:数据 输入 于输入      更新时间:2023-10-16

我试图编写一个有关查找两个序列中间的程序,这并不难,但是我停止购买输入两个序列部分。

以前从未考虑过,总是尝试过while(cin>> temp),但不知道为什么这次失败了。

当我对其进行编译时,第一个循环输入就可以了,但是当第二个循环开始时,编译器会发出"矢量迭代器不可用"

#include <iostream>
#include <vector>
using namespace std;
template< class T>
T median(vector<T>& s1, vector<T>& s2) {
T m(0);
auto itr1 = s1.begin();
auto itr2 = s2.begin();
int counts = (s1.size() + s2.size() -1 ) / 2 ;
    for (int i = 0; i < counts; ++i){
        if ((*itr1 < * itr2) && ( itr1+1 != s1.end()))
            ++itr1;
        else
            ++itr2;
    }
    m = (*itr1 + *itr2) / 2;
    return m;
}
int main() {
    vector<int> s1; 
    vector<int> s2;
    cout << " Please input the number in the first sequence " << endl;
    int temp;
    while (cin >> temp) {
        s1.push_back(temp);
    }
    cout << " Please input the number in the second sequence " << endl;
    int temp2;
    while (cin >> temp2){
        s2.push_back(temp2);
    }
    cout << " The median of these two sequences is " << median<int>(s1, s2) << endl;
    return 0;
}

您可以使用非数字输入作为符号来停止。它将停止在任何键上,不仅" Q",还可以添加其他支票等。

cout << " Please input first sequence numbers (press 'q' to finish)" << endl;
while (cin >> temp)
    s1.push_back(temp);
cin.clear();
// ignore all symbols before 'n'
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
cout << " Please input second sequence numbers (press 'q' to finish)" << endl;
while (cin >> temp)
   s2.push_back(temp);