我一直试图根据以下两者之间的选择在阵列中搜索特定的汽车(阵列):汽缸,型号,年份或汽缸数,并在此处从屏幕上显示通过搜索检索到的项目。 我在此处显示的文本文件中的数据已经传递到数组中,并打印为:
Volkswagen
Jetta
2016
4
Jeep
Wrangler
2008
6
Toyota
Corolla
1999
4
Chevy
Malibu
2018
6
Chevy
Malibu
2014
6
BMW
320i
2014
6
Jeep
GrandCharokeeLaredo
2006
6
Ford
Fusion
2012
4
Chevy
Equinox
2015
4
Volkswagen
Jetta
1998
4
我的问题是我不知道如何从菜单中的用户输入(例如:“大众汽车”)进行传输,并显示具有该特性的阵列。
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <time.h>
#include <math.h>
using namespace std;
class Cars
{
private:
// Private variables of cars
string make;
string model;
int year;
int cylinders;
public:
// Function within the objects
void setMake(string m) { make = m; }
string getMake() { return make; }
void setModel(string mo) { model = mo; }
string getModel() { return model; }
void setYear(int y) { year = y; }
int getYear() { return year; }
void setcylinders(int c) { cylinders = c; }
int getCylinders() { return cylinders; }
};
int main()
{
//Opening the file
ifstream inputFile;
inputFile.open("cars.txt");
// Variables for car characteristics
string make;
string model;
int year;
int cylinders;
string inMa;
string inMo;
int inYe;
int inCy;
// Object array
Cars car[10];
cout << " Display of available automobiles: " << endl;
cout << endl;
// Reading from file and passing into array
for (int x = 0; x < 10; x++)
if (inputFile >> make >> model >> year >> cylinders)
{
car[x].setMake(make);
car[x].setModel(model);
car[x].setYear(year);
car[x].setcylinders(cylinders);
cout << right << setw(7) << " Car #" << x << " " << endl;
cout << "Maker: " << make << endl;
cout << "Model: " << model << endl;
cout << "Year made: " << year << endl;
cout << "Number of cylinders: " << cylinders << endl;
cout << endl;
}
inputFile.close();
int selection;
cout << " Selection of automobiles:" << endl;
cout << " Select an option to describe your car/cars. " << endl;
cout << " ----------------------------" << endl;
cout << " 1. Maker of Car: " << endl;
cout << " 2. Model of Car: " << endl;
cout << " 3. Year of the Car made: " << endl;
cout << " 4. Number of cylinders: " << endl;
cin >> selection;
if (selection == 1)
{
cout << " Who is the maker of the car? " << endl;
// Need help displaying array that contain a specific variable
// Ex: All arrays that contain "Jeep"
}
else if (selection ==2)
{
cout << " What is the model of the car? " << endl;
// Need help displaying array that contain a specific variable
}
else if (selection ==3)
{
cout << " What was the year the car was made? " << endl;
// Need help displaying array that contain a specific variable
}
else if (selection ==4)
{
cout << " How many cylinders does the car have?" << endl;
// Need help displaying array that contain a specific variable
}
else
{
cout << "Enter a valid response" << endl;
}
system("pause");
return 0;
}
如何将数组与用户输入匹配,并根据对象数组将其输出给用户?我不担心用户在“ cin”期间是否错误输入了变量。