I am writing a simple program that takes user input to push_back ints into a vector I want to limit the range of ints they can enter. I have no idea how to implement an if statement using my parameters as a test within the while loop I use to enter in data to the vector. just using a standard syntax to enter data and don't have a solid working prototype for the error handling.
int main()
{
cout<<"Enter positive whole numbers 1-15."<<endl;
vector <int> myvec;
int nums;
while(cin>>nums)
{
myvec.push_back(nums);
}
for(int i=0;i<myvec.size();++i)
{
if((myvec[i]<1))
{
cout<<"Error: "<<myvec[i]<<" is an invalid input."<<endl;
cout<<"Please enter whole numbers 1-15. Your data has been cleared."<<endl;
myvec.erase(myvec.begin(),myvec.end());
while(cin>>nums)
{
myvec.push_back(nums);
}
break;
}
break;
}
I Have left out obviouse sections of my programing but when given the correct headers and all other needed syntax to compile it gives me a vector subscript out of range error. I know that it must be something with my iteration through the vec to check if the value of index [0] is less than one. Please any help or knowledge of this kind of error handling and strategy. Thank you
well no I would like only the offending input to be erased but I am also looking for the easiest solution and trying to avoid feature creep. The way you have this setup I believe nothing must be erased. I just tryed your code and was wondering if you tried to compile your answer becuase it does not work!!
> I would like only the offending input to be erased
The simplest way to achieve that would be: do not add the offending input to the vector in the first place.
> wondering if you tried to compile your answer becuase it does not work!!
I hadn't compiled it earlier; but I have done so now. And yes, it does not work; sorry about that.
The code has a stupid mistake - the if and else are switched around. The corrected code: