程序读取words.txt中的单词,随机抽取5个进行测试,用户输入英文后自动评分并保存结果到score.txt,包含文件操作、随机抽题与成绩记录功能。
用C++写一个带文件读写与评分功能的单词测试程序,核心是读取单词表、用户答题、自动评分并保存结果。下面是一个完整可运行的示例程序,包含详细说明。
1. 程序功能说明
程序从文件 words.txt 中读取单词和对应中文意思,随机抽取若干单词让用户输入英文拼写,答完后自动评分,并将用户成绩写入 score.txt 文件。
2. 准备单词文件(words.txt)
在程序同目录下创建 words.txt,格式为每行一个“英文 单词+空格+中文”:
立即学习“C++免费学习笔记(深入)”;
apple 苹果 banana 香蕉 cat 猫 dog 狗 hello 你好
3. C++代码实现
以下是完整代码:
#include <iostream> #include <fstream> #include <vector> #include <String> #include <sstream> #include <cstdlib> #include <ctime> using namespace std; <p>struct Word { string english; string chinese; };</p><p>vector<Word> loadWords(const string& filename) { vector<Word> words; ifstream file(filename); if (!file.is_open()) { cout << "无法打开单词文件!" << endl; return words; }</p><pre class='brush:php;toolbar:false;'>string line; while (getline(file, line)) { if (line.empty()) continue; stringstream ss(line); Word w; ss >> w.english >> w.chinese; if (!w.english.empty() && !w.chinese.empty()) { words.push_back(w); } } file.close(); return words;
}
void saveScore(const string& name, int correct, int total) { ofstream file(“score.txt”, ios::app); if (file.is_open()) { file << name << ” 答对:” << correct << “/” << total << ” (” << (total ? (correct * 100.0 / total) : 0.0) << “%)” << endl; file.close(); cout << “成绩已保存。n”; } else { cout << “无法保存成绩!n”; } }
int main() { vector<Word> words = loadWords(“words.txt”); if (words.empty()) { cout << “没有加载到单词,请检查 words.txt 文件。n”; return 1; }
srand(time(0)); int total = 5; // 每次测试5个单词 int correct = 0; string name; cout << "请输入你的名字:"; getline(cin, name); cout << "n开始测试!请输入下列中文对应的英文单词:nn"; for (int i = 0; i < total; i++) { int index = rand() % words.size(); Word& w = words[index]; string answer; cout << "(" << i+1 << ") " << w.chinese << ":"; getline(cin, answer); if (answer == w.english) { cout << "✔ 正确!n"; correct++; } else { cout << "✘ 错误,正确答案是:" << w.english << "n"; } } cout << "n测试结束!你的得分:" << correct << "/" << total << endl; saveScore(name, correct, total); return 0;
}
4. 功能特点
- 文件读取:从 words.txt 加载单词对
- 随机抽题:每次测试随机选择单词,避免重复记忆顺序
- 自动评分:对比用户输入与正确答案
- 成绩保存:将姓名、正确数、总题数和百分比追加写入 score.txt
- 错误处理:检查文件是否成功打开
5. 扩展建议
- 增加错题记录功能,保存用户答错的单词
- 支持多次测试后查看历史成绩
- 添加难度分级,按文件分组加载单词
- 支持忽略大小写判断答案
基本上就这些。这个程序结构清晰,适合初学者理解文件操作、结构体、随机数和字符串处理。只要确保 words.txt 和可执行文件在同一目录,就能正常运行。
评论(已关闭)
评论已关闭