当我尝试编译我正在处理的一些源代码时,我收到此错误。我对编程非常陌生,因为某些原因,数组一直给我带来困难:
airline2.cpp:9:84: error: too many initializers for ‘char [4]’
char array_seats[][4] = {{'1', '2', '3', '4', '5', '6', '7'},{'A', 'B', 'C', 'D'}};
这是我的源代码:
#include <iostream>
using namespace std;
int main()
{
char row, letter, answer;
int letter2;
char array_seats[][4] = {{'1', '2', '3', '4', '5', '6', '7'},{'A', 'B', 'C', 'D'}};
for (int row = 0; row <= 6; row++)
{
for (int letter = 0; letter <= 4; letter++)
{
cout << array_seats[row][letter] << " ";
}
cout << endl;
}
do
{
cout << "Enter your desired seat row:\n";
cin >> row;
cout << "Enter a seat letter:\n";
cin >> letter;
if(letter == 'A' || letter == 'a')
letter2 = 1;
else if(letter == 'B' || letter == 'b')
letter2 = 2;
else if(letter == 'C' || letter == 'c')
letter2 = 3;
else if(letter == 'D' || letter == 'd')
letter2 = 4;
if(array_seats[row-1][letter2] == 'X')
cout << "Sorry, this seat is taken.\n" << endl;
else
{
array_seats[row-1][letter2] = 'X';
cout << "Seat reservation successful.\n" << endl;
}
for (int row = 0; row <= 6; row++)
{
for (int letter = 0; letter <= 4; letter++)
{
cout << array_seats[row][letter] << " ";
}
cout << endl;
}
cout << "Would you like to try again? (Y/N)\n";
cin >> answer;
}while (answer == 'Y' || answer == 'y');
cout << "Have a good flight!\n";
return 0;
}
我尝试将错误设置为5并在结尾添加'\ 0',但似乎没有任何效果。有什么帮助吗?
答案 0 :(得分:2)
char array_seats[][4] = {{'1', '2', '3', '4', '5', '6', '7'},{'A', 'B', 'C', 'D'}};
{'1','2','3','4','5','6','7'}超过4
答案 1 :(得分:1)
您尝试初始化2D阵列的方式存在语法错误。
char array_seats[][4] = {{'1', '2', '3', '4', '5', '6', '7'},{'A', 'B', 'C', 'D'}};
上述行意味着每行将有4个元素。如果你看到第一行,它有7个元素,{'1','2','3','4','5','6','7'}。将此值减少为4个元素,编译错误将消失。所以你的array_seats现在有2行4列
注意:执行上述操作将解决编译错误,但您的程序会遇到严重的运行时错误。特别是当您尝试访问array_seats [2] [0]等时