在读取数据文件时,如何找到用户字符串输入的字谜?
Whilst reading through a datafile, how do I find anagrams of the user's string input?
基本上,我得到了一个包含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 "";
}
相关文章:
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- 用户输入字符串的文件附加问题..C++
- 从 cin 读取不会返回整个输入字符串
- 输出返回编号。等于输入字符串的单词的字符串数
- 控制台未正确读取输入字符串
- 使用终止程序的指针在数组中输入字符串
- 如何删除用户输入字符串末尾的空字符?
- 在循环中使用 cin.get() 输入字符串
- 如何从输入字符串中提取特定位置的字符?
- 用户输入字符串的结构的搜索向量
- 无法使用 getline() 输入字符串.它只读取一个字符串
- 如何在 c++ 中读取输入字符串,忽略空格
- FSTREAM的问题读取确定,但不编写用户输入字符串
- boost::split会在输入字符串不是常量时更改输入字符串吗?
- 通过键盘输入字符串数组和 int 数组的数组大小
- Zlib 放气输入大于原始输入字符串的字符
- C 忽略输入字符串
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 我无法将 Excel 中的输入字符串存储为二维字符串
- 如何识别输入的输入字符串在 c++ 中是两个还是多个单词