我如何才能在一组对象中找到我需要的主要参与者



这是我的任务:

我已经完成了一半的代码,但我很挣扎,因为我是OOP的初学者,我不知道如何才能找到以安吉丽娜·朱莉为主角的电影。

for (int i = 0; i < n; ++i)
{
string name;
int year;
string prod;
string actor;
cout << "nenter the film name " ;
cin >> name;
cout << "nenter the production year ";
cin >> year;
cout << "nenter the producer name ";
cin >> prod;
cout << "nenter the actor name ";
cin >> actor;
obs[i].SetName(name);
obs[i].SetYearP(year);
obs[i].SetProducer(prod);
obs[i].SetMaina(actor);
if (actor == "Angelina Jolie")
{
cout << "The movie who has main actor Angelina Jolie is" << name << endl;
} // Тhis is my attempt.
}
}

您需要创建一个函数,在数组上循环并检查主要参与者:

bool findFilm(Film* films, int numFilms, string actor)
{
bool found = false;
for (int i = 0; i< numFilms; i++) {
if(!actor.compare(0, films[i].GetyMaina().length(), films[i].GetyMaina()){
cout<<"Film "<<films[i].GetName()<<" has main actor "<<actor<<"n";
found = true;
}
}
return found;
}

您应该做的第一件事是使用C++容器,如std::vector、std::array,而不是原始数组。当然,然后你应该填满它们。

std::vector<Films> films;
std::array<Films, 100> films;

第二件事是,你应该删除"Films((=default;"部分。该声明更改了C++中的所有内容。

在这些更改之后,您将能够使用容器的模板成员函数和算法函数(如find((、find_if((、count((等(来获得所需内容。

#include <algorithm>

如果你不能做这些改变,你可以简单地通过循环来做:

for(auto film : films){
//comparisons, if checks, returns
}

请使用getline((函数进行用户输入,因为cin >> name将从名称Angelina Jolie中仅保存Angelina。因为它只阅读完整的单词,不包括空白。

要使用函数getline((,请将其放在#include<cstring>之后

#include <string>

所以像这样使用getline:

cout << "n enter the actor name ";
std::getline (std::cin,actor);

另一个问题是,在两个输入之间需要cin.ignore((。因为您需要从中间的缓冲区中清除换行符。

在循环之前,要求这样的数据:

cout << "how many films ";
cin >> n;
cin.ignore();

像这样循环:

cout << "n enter the film name ";
getline(cin, name);
cout << "n enter the production year ";
cin.ignore();
cin >> year;
cout << "n enter the producer name ";
cin.ignore();
getline(cin, prod);
cout << "n enter the actor name ";
getline(cin, actor);

b( (将此函数放在类的公共部分中,位于字符串GetMania((之后(:

static void FindFilm(Film arr[], int cntFilms, string actor)
{
for (int i = 0; i < cntFilms; i++)
{
if (arr[i].GetMaina() == "Angelina Jolie")
cout << "The movie who has main actor Angelina Jolie is" << arr[i].GetName() << endl;
}
}

在循环之后,从main调用它。

string actor = "Angelina Jolie";
Film::FindFilm(obs, n, actor);

此外,最好在输出消息的末尾为新行(\n(编写转义序列(或特殊字符(。像这样:

cout << "The name of movie: n" << name;

最新更新