将值输入到向量中直到输入结束?

时间:2015-03-28 00:01:37

标签: c++ input vector

所以我希望用户输入这样的内容:

0 15 72 34 92 8

我想用这些数字填充整数向量。

这就是我所拥有的:

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

int main()
{
    vector<int> V;
    cout << "Please enter the numbers separated by \n";
    cout << "spaces, then press the \"Enter\" key.\n\n";

    int temp;
    while (cin >> temp)
    {
        V.push_back(temp);
    }
// The programs gets to this point and continuously asks for input



// Print the vector
    cout << "The vector contains [ ";
    for(int i = 0; i < V.size(); i++)
        cout << V.at(i) << " ";
    cout << "], ";

}

1 个答案:

答案 0 :(得分:0)

根据此示例修改代码。它需要用户输入,直到用户输入-1。

#include <iostream>
#include <vector>

using namespace std;    

int main()
{
    int number;
    vector<int> userInput;

     do
     {
        cout << "Enter a number (-1 to quit): ";
        cin >> number;

        userInput.push_back(number);

     } while (number != -1);

    for (vector < int >::iterator it = userInput.begin(); it < userInput.end() - 1; it++)
    {
        cout << endl << *it;
    }

    system("pause");
    return 0;
}