程序读取words.txt中的单词,随机抽取5个进行测试,用户输入英文后自动评分并保存结果到score.txt,包含文件操作、随机抽题与成绩记录功能。

用C++写一个带文件读写与评分功能的单词测试程序,核心是读取单词表、用户答题、自动评分并保存结果。下面是一个完整可运行的示例程序,包含详细说明。
程序从文件 words.txt 中读取单词和对应中文意思,随机抽取若干单词让用户输入英文拼写,答完后自动评分,并将用户成绩写入 score.txt 文件。
在程序同目录下创建 words.txt,格式为每行一个“英文 单词+空格+中文”:
立即学习“C++免费学习笔记(深入)”;
apple 苹果 banana 香蕉 cat 猫 dog 狗 hello 你好
以下是完整代码:
#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开始测试!请输入下列中文对应的英文单词:\n\n";
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;}
基本上就这些。这个程序结构清晰,适合初学者理解文件操作、结构体、随机数和字符串处理。只要确保 words.txt 和可执行文件在同一目录,就能正常运行。
以上就是C++单词测试程序 文件读写与评分功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号