添加对输入单词包含非字母字符的检查代码#include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> #include <iterator> using namespace std; typedef istream_iterator<string> string_input; void welcome() { cout << "******************* 变位词查找系统*********************\n" << "在词典中找出给定的字符串的所有变位词" << endl; } void readDict(vector<string> & dictionary) { cout << "首先,请输入词典的文件名称:" << endl; string dictionary_name; cin >> dictionary_name; ifstream ifs(dictionary_name.c_str()); if (!ifs.is_open()) { cerr << "异常:文件"<< dictionary_name << "没有找到 " << endl; exit(1); } cout << "词典读入中 ..." << flush; copy(string_input(ifs), string_input(), back_inserter(dictionary)); sort(dictionary.begin(),dictionary.end()); cout << "词典包含有 " << dictionary.size() << " 个单词\n\n"; ifs.close(); } void analyseAnagram(const vector<string> & dictionary) { cout << "请输入单词(或任意字母序列)" << endl; for (string_input p(cin); p != string_input(); ++p) { cout << "查找输入单词的变位词中..." << endl; string word = *p; sort(word.begin(), word.end()); bool found_one = false; do { if (binary_search(dictionary.begin(), dictionary.end(), word)) { cout << " " << word ; found_one = true; } } while (next_permutation(word.begin(), word.end())); if (!found_one) cout << " 抱歉,没有找到变位词\n"; cout << "\n请输入下一个单词 " << "(或输入Ctrl+Z终止程序 ) \n" << endl; } } int main() { welcome(); vector<string> dictionary; readDict(dictionary); analyseAnagram(dictionary); system("pause"); return 0; }
时间: 2024-03-13 18:47:34 浏览: 67
C++常用的#include头文件总结
为了添加对输入单词包含非字母字符的检查,我们可以在 `analyseAnagram` 函数中在读入单词后进行检查,如果包含非字母字符,则提示用户重新输入单词。修改后的 `analyseAnagram` 函数如下:
```c++
void analyseAnagram(const vector<string> & dictionary) {
cout << "请输入单词(或任意字母序列)" << endl;
for (string_input p(cin); p != string_input(); ++p) {
string word = *p;
// 检查单词是否包含非字母字符
if (find_if(word.begin(), word.end(), [](unsigned char c) { return !isalpha(c); }) != word.end()) {
cout << "错误:输入单词包含非字母字符,请重新输入\n" << endl;
continue;
}
cout << "查找输入单词的变位词中..." << endl;
sort(word.begin(), word.end());
bool found_one = false;
do {
if (binary_search(dictionary.begin(), dictionary.end(), word)) {
cout << " " << word;
found_one = true;
}
} while (next_permutation(word.begin(), word.end()));
if (!found_one)
cout << " 抱歉,没有找到变位词\n";
cout << "\n请输入下一个单词 "
<< "(或输入Ctrl+Z终止程序 ) \n" << endl;
}
}
```
修改后,如果输入的单词包含非字母字符,会提示用户重新输入单词。
阅读全文