Why wont this while loop stop? [c++] -
i cant understand why while loop isnt stopping 1 time end status matched? thought user inputs 5 digit integer , can type else terminate input process.
bool noerror(true); int n(0),part2temp; vector<int> part2; while(noerror){ cout << "please come in 5 integer (x stop)" << endl; cin >> part2temp; part2.push_back(part2temp); n++; if (cin.fail()||part2temp>99999||part2temp<10000){ cout << "end status matched" << endl; cin.clear(); cin.ignore(10); noerror=(false); } } cout << "escaped loop" << part2[n] << endl;
i output screen if part of loop when type in x illustration reason changing bool value not terminate loop , text "escaped loop" never shown on screen. can tell me i'm doing wrong? thanks
there undefined behaviour part2[n]
going 1 beyond bounds of vector
, , may reason output of next line of code never appears:
cout << "escaped loop" << part2[n] << endl;
giving impression loop not exit. if loop executes 1 time n == 1
, there 1 element in vector
named part2
, means part2[0]
valid. confirm utilize vector::at()
, wrap in try{}catch(std::out_of_range&)
block:
try { cout << "escaped loop" << part2.at(n) << endl; } grab (std::out_of_range const&) { std::cerr << "access out of range\n"; }
to correct, confirm vector
not empty()
, utilize either [n - 1]
or vector.back()
.
c++ while-loop boolean
No comments:
Post a Comment