C++测验生成器开发:如何打乱词与定义配对并写入文件?
解决配对题定义打乱问题的C++实现
问题分析
你当前的代码通过单独变量(如connectword1、connectdef1)存储词与定义,不仅扩展性差(新增题目需修改代码),也无法便捷地打乱定义顺序以生成配对题。
改进方案
使用STL容器存储数据,配合随机打乱算法实现需求,步骤如下:
- 用
std::vector统一存储所有词和对应的正确定义,提升灵活性; - 复制正确定义到新容器,通过
std::shuffle打乱顺序; - 按固定格式对齐词与打乱后的定义,写入文件。
修改后的完整代码
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <random> #include <string> int current_numbered_question; // 根据你的代码全局变量保留,建议改为参数传递 void connectDefinitions() { std::fstream file("quiz.txt", std::ios::app); if (!file.is_open()) { std::cout << "Error when opening file.\n"; return; } std::vector<std::string> words; std::vector<std::string> correct_definitions; // 收集4组词与定义 for (int counter = 0; counter < 4; ++counter) { std::string user_word, user_def; std::cout << "What is the word you would like to add?\n"; // 仅在非首次输入时忽略换行符,避免吞掉输入 if (counter != 0) { std::cin.ignore(); } std::getline(std::cin, user_word); std::cout << "What is the definition of the word you added?\n"; std::getline(std::cin, user_def); words.push_back(user_word); correct_definitions.push_back(user_def); } // 写入题目标题 file << current_numbered_question << ".) Connect the definitions to the word.\n\n"; // 复制定义并打乱顺序 std::vector<std::string> shuffled_definitions = correct_definitions; std::random_device rd; std::mt19937 g(rd()); std::shuffle(shuffled_definitions.begin(), shuffled_definitions.end(), g); // 格式化输出(对齐处理) const int word_width = 20; // 可根据最长词调整宽度 for (size_t i = 0; i < words.size(); ++i) { file << words[i]; // 填充空格保证对齐 if (words[i].length() < word_width) { file << std::string(word_width - words[i].length(), ' '); } file << shuffled_definitions[i] << '\n'; } file << "\n"; file.close(); }
关键细节说明
- 容器替代单独变量:
std::vector让新增题目只需修改循环次数,无需新增变量,扩展性更强; - 真随机打乱:使用
std::random_device生成随机种子,配合std::mt19937随机引擎,确保每次打乱结果不同; - 输入修复:调整
cin.ignore()的调用时机,解决原代码中第一次输入被吞的问题; - 排版对齐:通过固定宽度和空格填充,实现和示例一致的规整排版。
额外优化建议
- 尽量避免全局变量(如
current_numbered_question),改为函数参数传递,提升代码模块化程度; - 添加输入验证逻辑,防止用户输入空的词或定义。
内容的提问来源于stack exchange,提问作者JUNKJACKZACK
相关产品推荐
相关产品推荐

