C++无法退出while循环
问题描述:
因此,对于我的操作矢量的程序,在每个开关盒的末尾会出现一个选项:如果输入字母'q'
,程序应该退出while循环并结束程序,但是当我输入信'q'
时,程序崩溃而不是正常退出。这是为什么发生?这是一个无限循环吗?C++无法退出while循环
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int rnum;
int jnum;
int i;
int lim = 5;
char choice='b';
vector<int> jersey(lim);
vector<int> rating(lim);
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "" << endl;
cout << "Choose an option:" << endl;
cin >> choice;
while(choice != 'q') {
switch(choice) {
case 'a' :
// addplayer
for(int i = 0; i<=lim-1; i++)
{
cout << "Enter a new player's jersey number:" << endl;
cin >> jersey.at(i);
cout <<"Enter the player's rating:" << endl;
cin >> rating.at(i);
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'u' :
// updat rating
cout << "Enter a jersey number:" << endl;
cin >> jnum;
for(int i = 0; i <= lim-1; i++)
{
if(jersey.at(i) == jnum)
{
cout << "Enter a new rating for player:" <<endl;
cin >> rnum;
rating.at(i) = rnum;
break;
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'o':
cout << "ROSTER" << endl;
for(int i = 0; i<lim; i++)
{
cout << "Player "<<i+1 <<" -- Jersey number:" << " " <<jersey.at(i) << ", " << "Rating: " << rating.at(i) << endl;
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'd':
cout << "Enter a jersey number:" << endl;
cin >> jnum;
for(std::vector<int>::iterator spot = jersey.begin(); spot != jersey.end(); ++spot)
{
if(*spot == jnum)
{
jersey.erase(spot);
rating.erase(spot);
lim = jersey.size();
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
case 'r':
cout << "Enter a rating:" << endl;
cin >> rnum;
for(int i = 0; i <= lim-1; i++)
{
if(rating.at(i) >= rnum)
{
cout << "Player "<<i+1 <<" -- Jersey number:" << " " <<jersey.at(i) << ", " << "Rating: " << rating.at(i) << endl;
}
}
cout << "Choose an option:" << endl;
cin >> choice;
break;
default:
cout << "Choose an option:" << endl;
cin >> choice;
break;
}
}
return 0;
}
答
您的case 'd'
看起来不正确。您不能使用spot
从rating
中删除一个元素,因为spot
只能遍历jersey
的元素。为了解决这个问题,并有可能解决您的崩溃或无限循环的问题,您可以将以下代码:
if(*spot == jnum)
{
jersey.erase(spot);
rating.erase(spot);
lim = jersey.size();
}
有了:
if(*spot == jnum)
{
jersey.erase(spot);
rating.erase(rating.begin() + (spot - jersey.begin()));
lim = jersey.size();
}
这里,spot - jersey.begin()
会给你球衣的指数你刚才发现,并补充说,rating.begin()
将因此给你相应的评级,并允许你正确地从rating
载体中删除它。
此外,由于您的代码允许重复的球衣号码,因此删除重复项并不总是会删除该号码的所有实例。如果你想解决这个问题,你可以在lim = jersey.size();
之后加spot--;
,以确保你不会跳过重复的元素。
最好的工具是你的调试器... – Charles
你有没有考虑格式化你的代码,使其可读? –
你的格式将会让你感到兴奋。事实上,我没有看到任何错误。你滥用向量就好像它们是简单的数组一样......你的意思是“程序崩溃而不是正常退出”? (或者给我们一些准确的输入来复制失败。) –