我无法弄清楚如何将2d数组作为参数传递。我发现的C ++手册和其他示例并没有给我太多帮助,也许有人可以帮助我了解更多,如果他们看看我的代码。感谢
标题
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype>
#include <cstdlib>
#include <string>
using namespace std;
void extern readFile(ifstream&, int&, int&, int&, int&, int[][6]);
void extern userInput(int&, int&, int&, int&, int&, int&, char&, char&, int[][6]);
void extern findSeats(int&, int&, int&, int&, int&, int&, char&, char&, int[][6]);
#endif // HEADER_H_INCLUDED
主要
#include "header.h"
int main()
{
ifstream inFile;
int FC_Row, FC_Col, EconRow, EconCol, ticketNum, rowNum;
int airplane[100][6];
char ticketType, seatType;
cout << setw(48) << "Thank you for choosing Cheeta Airlines!" << '\n' << '\n' << endl;
ifstream inData;
inData.open("Airplane.txt");
if (!inData)
{
cout << "Cannot open the input file."
<< endl;
return 1;
}
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane[100][6]);
userInput(FC_Row, FC_Col, EconRow, EconCol, ticketNum, rowNum, ticketType, seatType, airplane[100][6]);`
}
READFILE:
#include "header.h"
void readFile(ifstream& inFile, int& FC_Row, int& FC_Col, int& EconRow, int& EconCol, int airplane[][6])
{
int a, b;
inFile.open("Airplane.txt");
inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;
for (a = 0; a < FC_Row; a++)
for (b = 0; b < FC_Col; b++)
inFile >> airplane[a][b] ;
for (a = 0; a < EconRow; a++)
for (b = 0; b < EconCol; b++)
inFile >> airplane[a + FC_Row][b] ;
cout << setw(11)<< "A" << setw(6) << "B"
<< setw(6) << "C" << setw(6) << "D"
<< setw(6) << "E" << setw(6) << "F" << endl;
cout << " " << endl;
cout << setw(30) << "First Class: $2,000" << endl;
cout << '\n';
for (a = 0; a < FC_Row; a++)
{
cout << "Row " << setw(2) << a + 1 << ":";
for (b = 0; b < FC_Col; b++)
cout << setw(5) << airplane[a][b] << " ";
cout << endl;
}
cout << '\n';
cout << setw(30) << "Economy Class: $750" << endl;
cout << '\n';
for (a = FC_Row; a < (EconRow + FC_Row); a++)
{
cout <<"Row " << setw(2)<< a + 1 << ":";
for (b = 0; b < EconCol; b++)
cout << setw(5) << airplane[a][b] << " ";
cout << endl;
}
}
答案 0 :(得分:3)
如果您需要传递2D数组 -
void extern readFile(ifstream&, int&, int&, int&, int&, int[][6]);
void readFile(ifstream&, int&, int&, int&, int&, int[][6])
{
// ....
}
呼叫应该是 -
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane);
当你说 -
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane[100][6]);
您实际上是在该位置传递值(即int
)。但该函数需要int [][6]
。
答案 1 :(得分:1)
最后一个参数声明为int
,但2D int数组的类型为int[][depth]
。
将readFile
原型声明更改为:
void extern readFile(ifstream&, int&, int&, int&, int&, int[][6]);
稍后,当您调用该函数时,您将传递数组int
中的元素:
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane[100][6]);
该函数需要一个类型为int[][6]
的2D int数组,因此您必须只传递变量本身,而不传递任何索引:
readFile(inFile, FC_Row, FC_Col, EconRow, EconCol, airplane);
答案 2 :(得分:0)