Also für mein Programm der Manipulation eines Vektors, wird eine Auswahl am Ende jedes Schalters Fall präsentiert: Wenn der Buchstabe 'q'
eingegeben wird, soll das Programm die While-Schleife beenden und das Programm beenden, aber wenn ich den Buchstaben eingeben 'q'
, stürzt das Programm ab, anstatt richtig zu beenden. Warum passiert dies? Ist es eine Endlosschleife?C++ kann nicht while-Schleife verlassen
#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;
}
Das beste Werkzeug dafür ist Ihr Debugger ... – Charles
Haben Sie überlegt, Ihren Code so zu formatieren, dass er lesbar ist? –
Ihre Formatierung wird Sie stolpern. So wie es ist, sehe ich keinen Fehler. Sie missbrauchen Vektoren, als ob sie einfache Arrays wären ... Was meinen Sie mit "das Programm stürzt ab, statt richtig zu beenden"? (Das oder geben Sie uns eine genaue Eingabe, die den Fehler repliziert.) –