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

标签 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;
}

最佳答案

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

关于c++ - find() STL 算法...我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13318892/

相关文章:

C++ STL vector 排序——破坏和归零

c++ - 为什么我生成的 .sln 文件不能在 Visual Studio 2010 中打开?

c++ - 为什么我在包含加载程序 header 时无法使用 OpenGL 函数?

string - 正则表达式捕获不会像我认为的那样长

c - 如何在 C 结构体中声明字符串?

c++ - C++ 中真正空的 std::vector 是什么?

C++ 在模板编译器错误中使用模板

c++ - 如何在GDB中解释backtrace的模板函数签名?

string - 与空字符串串联会引发 ERR :INVALID DIM

C++ 用另一个 vector 初始化 vector