如何使用用户输入在2D数组中正确修改char数组元素?专门用于电影院座位

时间:2019-03-21 22:59:06

标签: c++ multidimensional-array

我一直在设计座位图,特别是要模拟电影院使用2D字符数组的行和列的座位。我用字符“#”初始化了数组,以表示座位空了。但是,我想让用户能够选择行和列来选择他们想要的座位,并将数组中的该元素替换为“ *”以表示已使用。事情是我输入了一个用户输入,因此它“应该”用坐下来的座位修改和更新座位表,但是相反,它显示的座位好像从未坐过。

#include <iostream>
#include <iomanip>

//Global variable.
char seatingChart[15][30];

//Function prototype.
void theaterDisplay();

using namespace std;

int main()
{
   int choice;
   int row;
   int col;

//initializing all elements in array with '#'.
for(int i = 0; i < 15; i++)
{
    for(int j = 0; j < 30; j++)
        seatingChart[i][j] = '#';
}

//Loop to let user input the seat they want.
while(true)
{
    //Calling function to display seats so user can decide.
    theaterDisplay();

    cout << "Enter row: ";
    cin  >> row;
    cout << "Enter col: ";
    cin  >> col;

    if(seatingChart[row-1][col-1] == '*')
    {
        cout << "Seat is taken.\n";
    }
    else
    {
        seatingChart[row-1][col-1] == '*';
    }

}

}

//This function is simply just to display the seats available.
void theaterDisplay()
{
cout << endl << setw(25) << "Seats\n";
cout << "\t123456789012345678901234567890\n";

for(int i = 0; i < 15; i++)
{
    cout << "row " << (i + 1) << "\t";

    for(int j = 0; j < 30; j++)
    {
        cout << seatingChart[i][j];
    }
    cout << endl;
}
}

如果您能确定我做错了什么,Id会感激,因为我觉得它应该可以正常工作,但是由于某些原因,当用户输入行时,它不会覆盖数组中*的#和列。随意粘贴并运行它。希望我的代码简单明了,如果您需要澄清,请告诉我。预先感谢!

1 个答案:

答案 0 :(得分:1)

seatingChart[row-1][col-1] == '*';

应阅读

seatingChart[row-1][col-1] = '*';