我不明白为什么这个while循环不停止,一旦结束条件匹配?为什么这个while循环停止?
这个想法是用户输入一个5位数的整数,并可以键入其他任何东西来终止输入过程。但
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;
我得到的输出从循环的中频部分的画面时,我在X的例子,但由于某些原因改变布尔值不会终止循环和文本输入“逃脱环”从未在屏幕上显示。
谁能告诉我我做错了什么?
有几件事:首先,矢量中的索引从[0 ... n]开始,所以'part2 [n]'索引一个超过结尾。第二,你不需要跟踪矢量中元素的数量,“std :: vector”为你做这件事;使用'part2.size()'来获取值。第三,假设vector非空,'part2.back()'是访问最后一个元素的最简单方法。 – 2013-02-18 09:26:56
什么样的最终条件(你有三个)不符合你的期望?他们全部?? – WhozCraig 2013-02-18 09:27:00
另外,您应该检查是否在访问'part2temp'(即'push_back'之前)之前_before_失败。 (你应该在循环中定义'part2tmp',而不是在其外面。) – 2013-02-18 09:28:35