背单词软件开发c++
时间: 2023-12-22 21:27:39 浏览: 72
以下是一个简单的背单词软件的C++代码示例:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
// 定义单词结构体
struct Word {
string english;
string chinese;};
// 读取单词列表
vector<Word> readWords(string filename) {
vector<Word> words;
ifstream infile(filename);
if (!infile) {
cerr << "无法打开文件 " << filename << endl;
exit(1);
}
string line;
while (getline(infile, line)) {
size_t pos = line.find(",");
if (pos == string::npos) {
cerr << "文件格式错误" << endl;
exit(1);
}
string english = line.substr(0, pos);
string chinese = line.substr(pos + 1);
words.push_back({english, chinese});
}
return words;
}
// 随机选择一个单词
Word selectWord(const vector<Word>& words) {
int index = rand() % words.size();
return words[index];
}
// 提示用户输入单词的中文意思,并返回用户输入的结果
string getAnswer(const Word& word) {
cout << "请输入 " << word.english << " 的中文意思:";
string answer;
cin >> answer;
return answer;
}
// 检查用户输入的答案是否正确
bool checkAnswer(const Word& word, const string& answer) {
return word.chinese == answer;
}
int main() {
// 读取单词列表
vector<Word> words = readWords("words.txt");
// 初始化随机数生成器
srand(time(nullptr));
// 开始背单词
while (true) {
// 随机选择一个单词
Word word = selectWord(words);
// 提示用户输入单词的中文意思,并获取用户输入的结果
string answer = getAnswer(word);
// 检查用户输入的答案是否正确
if (checkAnswer(word, answer)) {
cout << "回答正确!" << endl;
} else {
cout << "回答错误,正确答案是 " << word.chinese << endl;
}
// 提示用户是否继续背单词
cout << "是否继续背单词?(y/n)";
char choice;
cin >> choice;
if (choice != 'y' && choice != 'Y') {
break;
}
}
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)