I have been trying to create a simple while loop to cin numbers into a vector, with some basic input validation. However, I am finding some weird things happening with my code. I am trying to have it so that the user can input numbers until they type in '0', which will then end the loop. This works fine.
However, I am also trying to make it so that if they enter a non-int (i.e. 3.4, a), or if they enter a negative number, it couts "BAD INPUT" and then quits the program. When I type in a negative number, it works fine. But when I type in a non-int, it does not cout anything, but still quits the program...
Likewise, I am also trying to have it so that if they type in '0' first, without having put in any numbers beforehand, it couts "NO NUMBERS" and quits the program. This one also quits the program, but again, does not cout anything.
My code is as follows:
#include <iostream>
#include <vector>
//I know it is considered bad practice for the below part.
using namespace std;
int main()
{
vector<int> numberStorage;
while (cin) {
int numInput = 0;
cin >> numInput;
if (numInput == 0) break;
if (!cin || numInput < 0) {
cout << "BAD INPUT" << '\n';
return false;
}
if (numInput == 0 && numberStorage.size() == 1) {
cout << "NO NUMBERS" << '\n';
return false;
}
numberStorage.push_back(numInput);
}
return 0;
}
Can anyone help me and clarify as to where my logic/code is going wrong here on these input validations? Thank you for any help.