私は C++ を勉強していて、構造を作成して操作する必要がありますAirplane
。
私の構造Airplane.h
#include "stdafx.h"
using namespace std;
struct Airplane {
string destination;
int number;
string type;
};
そしてそれは私のコードです
#include "stdafx.h"
#include "Airplane.h"
string SetDestination(int n);
string SetType(int n);
void PrintAirplaneList(Airplane * &airplaneList, int n, string title);
void SortByDestination (Airplane *&airplaneList, int n);
void FindAirplanesAndPrint(Airplane *&airplaneList, int n, string type);
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
srand((unsigned)time(NULL));
int n;
cout << "Input n = ";
cin >> n;
Airplane * airplaneList = new Airplane[n];
for (int i = 0; i < n; ++i)
{
airplaneList[i].destination = SetDestination(rand()%5);
airplaneList[i].number = rand()%9001 + 1000;
airplaneList[i].type = SetType(rand()%3);
}
PrintAirplaneList(airplaneList, n, "List:");
SortByDestination (airplaneList, n);
PrintAirplaneList(airplaneList, n, "Sorted list (by destination):");
string type;
cout << "Input type: ";
getline(cin, type);
FindAirplanesAndPrint(airplaneList, n, type);
delete [] airplaneList;
system("PAUSE");
return 0;
}
string SetDestination (int n)
{
string destination;
switch(n){
case 0: destination = "Tokio"; break;
case 1: destination = "Amsterdam"; break;
case 2: destination = "Moscow"; break;
case 3: destination = "Philadelphia"; break;
case 4: destination = "San Diego"; break;
default: destination = "Unknown city"; break;
}
return destination;
}
string SetType (int n)
{
string type;
switch(n){
case 0: type = "passenger"; break;
case 1: type = "cargo"; break;
case 2: type = "post"; break;
default: type = "unknown type"; break;
}
return type;
}
void PrintAirplaneList(Airplane *&airplaneList, int n, string title)
{
cout << "\n";
cout << title << "\n\n";
for (int i = 0; i < n; ++i)
{
cout << "Destination: " << airplaneList[i].destination << "\n";
cout << "Number: " << airplaneList[i].number << "\n";
cout << "Type: " << airplaneList[i].type << "\n\n";
}
}
void SortByDestination (Airplane *&airplaneList, int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n -1; ++j)
{
if(airplaneList[j + 1].destination > airplaneList[j].destination) continue;
Airplane tempAirplane = airplaneList[j];
airplaneList[j] = airplaneList[j + 1];
airplaneList[j + 1] = tempAirplane;
}
}
}
void FindAirplanesAndPrint(Airplane *&airplaneList, int n, string type) {
cout << "Type - " << type << "\n";
int count = 0;
for (int i = 0; i < n; ++i)
{
if (airplaneList[i].type == type)
{
cout << "Destination: " << airplaneList[i].destination << "\n";
cout << "Number: " << airplaneList[i].number << "\n";
++count;
}
}
if (count == 0)
{
cout << "Not found\n";
}
}
2 つの質問があります。
1. 入力できない
string type;
cout << "Input type: ";
getline(cin, type);
FindAirplanesAndPrint(airplaneList, n, type);
私の関数FindAirplanesAndPrint
は、型の値なしで機能し始めます。プログラムを作成して価値を得る方法は?
2. 関数内の動的配列のサイズを取得する方法は? すべての関数で配列のサイズを渡すn
方法が間違っているようです。