您的位置:首页 >C++单词测试程序:读写与评分功能详解
发布于2025-08-24 阅读(0)
扫一扫,手机访问
程序读取words.txt中的单词,随机抽取5个进行测试,用户输入英文后自动评分并保存结果到score.txt,包含文件操作、随机抽题与成绩记录功能。

用C++写一个带文件读写与评分功能的单词测试程序,核心是读取单词表、用户答题、自动评分并保存结果。下面是一个完整可运行的示例程序,包含详细说明。
程序从文件 words.txt 中读取单词和对应中文意思,随机抽取若干单词让用户输入英文拼写,答完后自动评分,并将用户成绩写入 score.txt 文件。
在程序同目录下创建 words.txt,格式为每行一个“英文 单词+空格+中文”:
apple 苹果 banana 香蕉 cat 猫 dog 狗 hello 你好
以下是完整代码:
#include <iostream> #include <fstream> #include <vector> #include <string> #include <sstream> #include <cstdlib> #include <ctime> using namespace std;struct Word { string english; string chinese; };
vector<Word> loadWords(const string& filename) { vector<Word> words; ifstream file(filename); if (!file.is_open()) { cout << "无法打开单词文件!" << endl; return words; }
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 和可执行文件在同一目录,就能正常运行。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9