1 2 3 4 5
|
cin >> b;
for (int i = 0; i <= b; ++i)
{
sum += numbers[i];
}
|
Your computer isn't going to like this is
b
winds up being bigger than (or equal to) the size of the vector.
Since you are just pushing the numbers into the vector, there's no need to enter
b
. The vector keeps track of how many items are in it.
1 2 3 4
|
for (int i = 0; i < numbers.size(); i++)
{
sum += numbers[i];
}
|
or
1 2 3 4
|
for (auto & num : numbers)
{
sum += num;
}
|
As for
why you need to use
cin.clear()
and
cin.ignore()
:
cin.clear()
: Arslan7041 explained it, but I want to add that subsequent calls to cin will fail unless you clear the fail state, even if you try to give valid input.
Technically speaking,
cin.clear()
will zero
all the error bits, so
cin.good()
will return true.
You can also use
ios::clear
to
set any of the iostate bits:
http://www.cplusplus.com/reference/ios/ios/clear/
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
: If cin failed to get valid input, the invalid input is still left in the stream. You must extract and discard that invalid input.
It's good to note that
cin.ignore()
without any parameters will by default only ignore 1 character. I could enter
ksjadgfka
and only the first character would be ignored, the rest would remain.
Doing
while (cin >> a)
is fine, it will just keep looping as long as it gets valid input. Inputting a non-numeric character will make cin fail and the loop no longer execute. But you now have to clear the fail bit and take care of the remaining garbage input.