Limiting number of elements in vector

无人久伴 提交于 2019-12-04 06:19:07

问题


Trying to limit the amount of inputs that a user could insert into a vector when inputting an array into 1 manually, but for some reason it's being weird.

#include <iostream>
using namespace std;

void fillVector(vector<int>& newThisIsAVector)
{
cout << "Please type in your 10 numbers separated by a space. On completion    press enter.";
int input;
cin >> input;

while (newThisIsAVector.size() < 10)
{
    newThisIsAVector.push_back(input);
    cin >> input;
}
cout << endl;
}

It's supposed to limit you at 10 but instead it's taking 10 then when you press enter it creates a new line. Then you type an 11th number and hit enter again. Then the script works and registers the first 10 numbers and does the other commands just fine, but with the first 10 numbers and completely ignores the unwanted 11th number. ;/

How do I fix it?


回答1:


You use cin once before the loop, and once inside the loop that is repeated 10 times. 1 + 10 equals 11 and therefore the input is asked for 11 times. To limit the number of inputs taken to 10, you need to limit the calls to cin to 10.




回答2:


Because when you record type your 10th elements, vector still have 9 elements. So on the next loop turn, you'll add the 10th in vector and ask for the 11th.

If you know it will be 10 elements to input, why not using C++11 std::array ?



来源:https://stackoverflow.com/questions/36029581/limiting-number-of-elements-in-vector

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!