【发布时间】:2018-07-11 07:18:23
【问题描述】:
我的代码有问题,我插入了一个循环,所以函数listOfSeats 总是被调用并且程序永远不会停止运行。问题是它只运行一次,我不能保证我在数组席位中更改的值已更改。我不知道为什么会这样,请帮忙。
当我添加一个调试器来查看它为什么崩溃时,我得到了这个ScreenShot 1和ScreenShot2。请帮助我真的不明白这是什么意思。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
string listOfSeats();
const int arraySize = 20;
int main() {
while(true) {
cout << "These are the type of seats we offer during the flight and their current status:\n";
cout << "(LW) Left Window\n(AL) Aisle left\n(AR) Aisle Right\n(RW) Right Window\n\n";
listOfSeats();
}
}
string listOfSeats() {
string typeOfSeat;
int numOfSeat;
static string seat[ arraySize ];
for ( int i = 0; i < 20; ++i )
seat[ i ] = "Available";
cout << setw( 5 )<< "Seat" << setw( 10 ) << "Status" <<endl;
for ( int lw = 0; lw < 5; ++lw )
cout << setw( 4 ) << "LW"<<lw+1 << setw( 12 ) << seat[ lw ] << endl;
for ( int al = 5; al < 10; ++al )
cout << setw( 4 ) << "AL"<<al-4 << setw( 12 ) << seat[ al] << endl;
for ( int rl = 10; rl < 15; ++rl )
cout << setw( 4 ) << "RL"<<rl-9 << setw( 12 ) << seat[ rl] << endl;
for ( int rw = 15; rw < 20; ++rw )
cout << setw( 4 ) << "AL"<<rw-14 << setw( 12 ) << seat[ rw] << endl;
cout << "\nPlease enter the type of seat you want to reserve (just the characters on brackets):";
for(;;) {
cin >> typeOfSeat;
if (typeOfSeat=="LW") {
cout <<"You have chosen a Left window seat.";
break;
}
else if(typeOfSeat=="AL") {
cout <<"You have chosen an Aisle left seat.";
break;
}
else if(typeOfSeat=="AR") {
cout <<"You have chosen an Aisle right seat.";
break;
}
else if(typeOfSeat=="RW") {
cout <<"You have chosen a Right window seat.";
break;
}
else {
cout <<"Invalid option entered. \nPlease enter a valid option:";
continue;
}
}
cout << "\nFrom the list presented above. Enter the number of the type of seat you want to reserve\n(just the number following the characters):";
for(;;) {
cin >> numOfSeat;
if (numOfSeat==1) {
cout <<"You have reserved the number "<< numOfSeat<<" "<<typeOfSeat<<" seat.";
break;
}
else if(numOfSeat==2) {
cout <<"You have reserved the number "<< numOfSeat <<" "<<typeOfSeat<<" seat.";
break;
}
else if(numOfSeat==3) {
cout <<"You have reserved the number "<< numOfSeat <<" "<<typeOfSeat<<" seat.";
break;
}
else if(numOfSeat==4) {
cout <<"You have reserved the number "<< numOfSeat <<" "<<typeOfSeat<<" seat.";
break;
}
else if(numOfSeat==5) {
cout <<"You have reserved the number "<< numOfSeat <<" "<<typeOfSeat<<" seat.";
break;
}
else {
cout <<"Invalid option entered. \nPlease enter a valid option:";
continue;
}
}
if (typeOfSeat=="LW") {
seat[ numOfSeat-1 ]="Reserved";
}
}
【问题讨论】:
-
这发生在哪些输入上?您是否尝试过附加调试器以查看您的程序是否崩溃?
-
请使用“switch-case”以确保仅根据条件运行单个逻辑。太多的 if-else 会造成混乱。对于第二个 if/else,您可以简单地将 numOfSeat 包含在您的消息中,而不需要任何 if/else
-
我刚刚做到了,它给我传递了一个我不太了解的信息。我用它所说的截图更新帖子,以便您提供帮助
-
提示:在将代码发布到 SO 之前,您可以使用 AStyle 等免费工具来修复代码格式。
-
你的
listOfSeats应该返回string