Функция поиска не возвращает ни одного имени - PullRequest
0 голосов
/ 06 мая 2020

Итак, я не могу заставить свою функцию поиска вернуться к фактическому названию фильмов с созданным массивом с заголовком mov ie, режиссером и актером. Я создаю массив объектов, создаю его экземпляр, запускаю do while l oop, чтобы получить позицию, и запускаю алгоритм поиска, чтобы получить заголовок, режиссера и актера mov ie. Но хоть убей, я не могу получить код, чтобы вернуть настоящее название, режиссера или актера. Он скажет, что имя есть в списке, но вернет пустое место. Я привел картинку ниже, чтобы показать возврат. Когда я добавляю mov ie в массив, он говорит, что mov ie не существует в массиве.

mov ie Class:

class Movies{
private:

    // variables
    string titleCode;
    string directorCode;
    string actorCode;

public:

    // constructors
    Movies()        // default constructor, allows no arguments.
    {
        //titleCode = "Home Movie"; directorCode = "Colin Powers"; actorCode = "Colin Powers";
    }
    Movies(string t, string d, string a) // constructor
    {
        titleCode = t; directorCode = d; actorCode = a;
    }

    // getter
    string getTitle() const
    {
        string title = titleCode;
        return title;
    }
    string getDirector() const
    {
        string director = directorCode;
        return director;
    }
    string getActors() const
    {
        string actors = actorCode;
        return actors;
    }

    // setters
    void setTitle(string t) // cout/cin were giving random "ambigious" error so i added std:: till they all stopped giving it.
    {
        std::cout << "Enter the title of the Movie: " << endl;
        std::cin >> t;
        titleCode = t;
    }
    void setDirector(string d)
    {
        std::cout << "Enter the Director of the Movie: " << endl;
        std::cin >> d;
        directorCode = d;
    }
    void setActors(string a)
    {
        std::cout << "Enter the main protagonist: " << endl;
        std::cin >> a;
        actorCode = a;
    }};

Массив фильмов:

Movies moviesArr[ARR_SIZE];

Прототип функции для функции поиска

int searchMovies(const Movies[], int, string);

Созданный массив объектов для поиска

Movies hollywood[ARR_SIZE] =
{ // title, director, actor
    Movies("Avatar", "James", "James"),
    Movies("Terminator", "John", "John"),
    Movies("Predator", "Michael", "Michael")
};

Выполните while, чтобы получить возвращенную позицию и имена:

do
                {
                    // get the movie title
                    cout << "Enter the movie title to search: " << endl;
                    cin >> title;

                    // search for the object
                    pos = searchMovies(hollywood, ARR_SIZE, title);

                    // if pos = -1 the title was not found
                    if (pos == -1)
                        cout << "That title does not exit in the list.\n";
                    else
                    {
                        // the object was found so use the get pos to get the description
                        cout << "The movie: " << moviesArr[pos].getTitle() << " is in the list. " << endl;
                        cout << "It was Directed by: " << moviesArr[pos].getDirector() << endl;
                        cout << "It also stars: " << moviesArr[pos].getActors() << endl;
                    }

                    // does the user want to look up another movie?
                    cout << "\nLook up another movie? (Y/N) ";
                    cin >> doAgain;

                } while (doAgain == 'Y' || doAgain == 'y');

Функция поиска для поиска по массиву:

int searchMovies(const Movies object[], int ARR_SIZE, string value){
int index = 0;          
int position = -1;      
bool found = false;     

while (index < ARR_SIZE && !found)
{
    if (object[index].getTitle() == value)  // if the title is found
    {
        found = true;       // set the flag.
        position = index;   // record the values subscript
    }
    index++;                // go to the next element.
}
return position;            // return the position or -1;}

вывод выглядит так: Неописуемый возврат, без имен, без директора, без заголовка.

1 Ответ

1 голос
/ 06 мая 2020

Эта строка:

Movies moviesArr[ARR_SIZE];

определяет пустой, неинициализированный массив Movies. Вы ищете конкретный Movie title в hollywood, который находит mov ie. Однако затем вы индексируете moviesArr:

 cout << "The movie: " << moviesArr[pos].getTitle() << " is in the list. " << endl;

, что является неопределенным поведением (и ничего не печатает для заголовка в вашем случае).

Замените это на:

 cout << "The movie: " << hollywood[pos].getTitle() << " is in the list. " << endl;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...