find()STL算法......我做错了什么?

Thu*_*erd 3 c++ string vector

目前,我正在尝试将C++的基础知识降低,因此学习使用find()算法就是我所处的位置.当我在我的代码中使用find()时,我遇到问题,当我正在寻找有多个单词时(例如:当我寻找FIFA时,我得到了我正在寻找的结果.但是当我寻找Ace Combat时,我得到一个无效的游戏输出).如果有人能说清楚我做错了什么,我会非常感激.

//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;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

问题是cin >> game;语句只读取输入的一个单词.因此,当用户输入"Ace Combat"时,您的程序会读取并搜索"Ace".要解决这个问题,请使用std::getline()读取整行而不是单个单词.例如,替换cin >> game;std::getline(cin, game);.