ThuggedOutNerd
ThuggedOutNerd

Reputation: 33

find() STL Algorithm... What am I doing wrong?

At the current moment, I'm trying to get the basics of C++ down so learning to use the find() Algorithm is where I'm at. When I use find() within my code, I am having problems when what I'm looking has more than one word (ex: when I look for FIFA I get the results I'm looking for. But when I look for Ace Combat, I get an Invalid game output). If anyone can shed any light on what I'm doing wrong, I'd greatly appreciate it.

//Games List
//Make a list of games I like and allow for user select one of the games

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<string>::const_iterator iter;

    vector<string> games;
    games.push_back("FIFA");
    games.push_back("Super Mario Bros.");
    games.push_back("Ace Combat");
    games.push_back("Sonic");
    games.push_back("Madden");

    cout << "These are my some of my favorite game titles.\n";
    for (iter = games.begin(); iter != games.end(); ++iter)
    cout << *iter << endl;

    cout << "\nSelect one of these games titles.\n";
    string game;
    cin >> game;    
    iter = find(games.begin(), games.end(), game);
    if (iter != games.end())
        cout << game << endl;
    else
        cout << "\nInvalid game.\n"; 
return 0;
}

Upvotes: 3

Views: 112

Answers (2)

snow
snow

Reputation: 36

the problem is at cin.

like cin >> game;

if you input "Ace Combat", game == "Ace".

it would stop at first blank.

Upvotes: 2

user405725
user405725

Reputation:

The problem is that cin >> game; statement reads only one word of the input. So when a user enters "Ace Combat", your program reads and searches for "Ace". To solve the problem, use std::getline() to read the whole line and not a single word. For example, replace cin >> game; with std::getline(cin, game);.

Upvotes: 6

Related Questions