[ad_1]
好吧,假设我制作了一个输入文件,其中包含单词及其含义。 所以我允许用户询问他们想要搜索的单词。 例如,用户想要搜索单词“time”,因此单词“time”在输入文件中,并且其含义将显示到终端。
但为什么我的输出显示未找到单词“time”,而单词“time”包含在输入文件中。
我尝试过的:
C++
case 2: { string searchWord; cout << "Enter the word to search: "; cin >> searchWord; bool found = false; string word, meaning; while (getline(inFile, word) && getline(inFile, meaning)) { if (searchWord == word) { char firstAlphabet = searchWord.at(0); cout << "Word " << searchWord << " found in the dictionary.\n\n"; cout << lineNum++ << "\t" << firstAlphabet << "\t" << searchWord << "\t" << meaning << endl; found = true; break; } } if (!found) { cout << "Word " << searchWord << " not found in the dictionary.\n"; } cout << "\nDone...\n"; break; }
解决方案1
下面的代码
C++
#include <iostream> #include <fstream> using namespace std; int main() { string searchWord; cout << "Enter the word to search: "; cin >> searchWord; bool found = false; ifstream inFile("dict.txt"); string word, meaning; size_t itemNum = 0; while (getline(inFile, word) && getline(inFile, meaning)) { if (searchWord == word) { char firstAlphabet = searchWord.at(0); cout << "Word " << searchWord << " found in the dictionary.\n\n"; cout << (itemNum+1) << "\t" << firstAlphabet << "\t" << searchWord << "\t" << meaning << endl; found = true; break; } ++itemNum; } if (!found) { cout << "Word " << searchWord << " not found in the dictionary.\n"; } cout << "\nDone...\n"; }
可以在我的 Linux 机器上运行,前提是输入文件结构正确(即任何内容的整行) 单词 接下来是一整行 词义; 例如,我的 字典.txt 是
money a current medium of exchange in the form of coins and banknotes time the indefinite continued progress of existence and events in the past, present, and future regarded as a whole universe all existing matter and space considered as a whole
[ad_2]
コメント