I can't understand why this while loop isn't stopping once the end condition is matched?
The idea is the user inputs a 5 digit integer and can type anything else to terminate the input process. But
bool noerror(true);
int n(0),part2temp;
vector<int> part2;
while(noerror){
cout << "Please enter the 5 integer (x to stop)" << endl;
cin >> part2temp;
part2.push_back(part2temp);
n++;
if (cin.fail()||part2temp>99999||part2temp<10000){
cout << "End condition matched" << endl;
cin.clear();
cin.ignore(10);
noerror=(false);
}
}
cout << "escaped loop" << part2[n] << endl;
I get the output to the screen from the IF part of the loop when I type in x for example but for some reason changing the bool value does not terminate the loop and the text "escaped loop" is never shown on screen.
Can anyone tell me what I'm doing wrong?
part2[n]indexes one beyond the end. And second, you don't need to keep track of the number of elements in the vector,std::vectordoes this for you; usepart2.size()to get the value. And third, supposing the vector non-empty,part2.back()is the simplest way of accessing the last element.part2temp(i.e. before thepush_back). (And you should probably definepart2tmpin the loop, and not outside of it.)ifblock, and when hit you can step to see what happens, and also examine the values of all relevant variables.