目前,我正在努力学习 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/