在读取数据文件时,如何找到用户字符串输入的字谜?

Whilst reading through a datafile, how do I find anagrams of the user's string input?

本文关键字:输入 字符串 用户 何找 数据 读取 文件      更新时间:2023-10-16

基本上,我得到了一个包含100个单词的数据文件,我的任务是编写一个字谜查找器以查找数据文件中的字谜。找到字谜后,我正在努力编码以打印出数据文件中的单词。

我设法将字符串按字母顺序排序以进行比较,并且我做了一个 if 语句来说明当前单词是否与原始字符串相同,然后打印出该单词。

如果这个问题听起来令人困惑,我深表歉意,我已经在这个问题上停留了几天,我根本无法解决这个问题。

string FindAnagram(string originalString) {
string currentWord;
string localString;
localString = originalString + currentWord;
ifstream dbFile;
dbFile.open(cDATAFILE);
while(!dbFile.eof()){
    getline(dbFile, currentWord);
      sort (currentWord.begin(), currentWord.end());
      sort (originalString.begin(), originalString.end());
if(currentWord == originalString){
          cout << "nt Anagram of the current word: " << localString << endl;
        }
        else {
          cout << "nt No anagram available." << endl;
        }
    }
dbFile.close();
return currentWord;
}
例如,如果当前单词是"alert",

那么它将通读数据文件并打印出单词"alert"的字谜,但我正在努力使其打印出数据文件中的单词。

例如,"稍后"应打印出来

,但"alert"将被打印出来。

提前谢谢。

数据文件中不再该单词,因为您使用排序操作对其进行了更改。

只需在执行此操作之前复制字符串,这样您仍然拥有原始字符串。

顺便说一下,localstring很奇怪;为什么当currentWord为空时,你还要附加currentWord

而且您不需要一遍又一遍地originalString排序。

std::string FindAnagram(const std::string& originalString)
{
    std::string originalStringSorted = originalString;
    std::sort(originalStringSorted.begin(), originalStringSorted.end());
    std::ifstream dbFile(cDATAFILE);
    std::string currentWord;
    while (std::getline(dbFile, currentWord))
    {
       std::string currentWordSorted = currentWord;
       std::sort(currentWordSorted.begin(), currentWordSorted.end());
       if (currentWordSorted == originalStringSorted)
       {
          std::cout << "Found '" << currentword << "' to be an anagram of '"
              << originalString << "'n";
          return currentWord;
       }
    }
    std::cout << "No anagram foundn";
    return "";
}