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?
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.
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