【发布时间】:2014-04-25 00:27:58
【问题描述】:
我必须将 txt 文件的每一行与用户输入变量进行比较。 如果用户输入的单词存在于 txt 文件中,它应该提示用户“该单词存在”。如果没有,则退出程序。
这是文本文件的样子:
hello
hey
wow
your
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("words.txt");
string content;
string userinput;
while(file >> content) {
cout << content << endl; // gets all the lines from the txt file
while(userinput != "exit") {
// asks user for input
cin >> userinput;
// compares two inputs
if (userinput == content)
{
cout << "The word exists." << endl;
} else {
break;
}
if (userinput == "exit") {
break;
}
}
}
return 0;
}
它不适合我。我能够返回 txt 文件中的所有单词,但无法将用户输入文本与 txt 文件中的 txt 行进行比较。任何帮助都会很棒。谢谢!
更新代码:
while(iFile >> content) {
while(userinput != "exit") {
// asks user for input
cin >> userinput;
// compares two inputs
if (content.find(userinput) != std::string::npos)
{
cout << "The word exists." << endl;
} else {
break;
}
if (userinput == "exit") {
break;
}
}
}
P.S:我对 c++ 很陌生。一个学生
【问题讨论】:
-
您正在对文件中的每个令牌运行一个循环,在其中您要求用户猜测,直到他放弃每个?不错,但不是你说的那样。
-
你想要做的:读取文件,将其解析为你保存在 unordered_set 中的令牌。然后询问用户应该匹配哪个词。
-
如果您需要性能提升,请先尝试将单词列表添加到 std::map 或 std::unordered_map (c++11)。然后运行一个 while 循环,在其中您要求用户输入并检查您的 std::map。必要时终止。