根据用户输入生成随机字母
Generate Random Letters Depending on User Input
我必须做一个简单的猜信游戏。到目前为止,我已经完成了几乎所有工作,但是当涉及到一项任务时,我不确定该怎么做。因此,在游戏开始之前,它会要求用户输入两件事:
输入不同字符的数量:(例如,如果输入 4,则选择的字母将从 A 到第 4 个字母,仅限 A-D)
和
输入图案长度:
模式长度输入工作正常,但我很难弄清楚如何修改生成代码函数以添加不同字符的数量。
有什么提示吗?
#include <iostream>
#include <random>
#include <string>
using namespace std;
size_t len;
string str;
void generate_code()
{
str.string::reserve(len);
random_device rd;
mt19937 gen{rd()};
uniform_int_distribution<char> dis{'A', 'Z'};
for (size_t i = 0; i < len; i++)
{
str += dis(gen);
}
}
void guess_checker()
{
string guess{};
size_t trial_count = 0, match_count = 0;
do
{
cout << "Enter your guess: " << endl;
cin >> guess;
if (guess.size() != len)
{
cout << "error: invalid guess" << endl;
}
else
{
match_count = 0;
for (size_t i = 0; i < len; i++)
{
if (guess[i] == str[i])
++match_count;
}
cout << "You guessed " << match_count << " character"
<< (match_count == 1 ? "" : "s") << " correctly." << endl;
}
++trial_count;
}
while (match_count != len);
cout << "You guessed the pattern in " << trial_count << " guess"
<< (trial_count == 1 ? "" : "es") << "." << endl;
}
int main()
{
int amount;
cout << "Enter the amount of different characters: ";
cin >> amount;
cout << "Enter the pattern length: ";
cin >> len;
generate_code();
guess_checker();
return 0;
}
只需将发电机行更改为:
uniform_int_distribution<char> dis{'A', 'A' + amount - 1};
我还建议事先添加一些验证,例如:
if (amount < 1 || amount > 26) {
cout << "Bad amount" << endl;
// exit or something
}
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么 Serial.println(<char[]>);返回随机字符?
- 字符串-C++后显示的随机字符
- C++如何通过用户输入删除列表元素
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- 使用开关大小写语句抽取随机扑克牌等级和花色以显示用户
- 如何使用C 随机显示用户输入字符串
- c++ 根据随机生成的数组检查用户输入的值
- 根据用户输入生成随机字母
- 有什么方法可以制作一个程序,随机选择10-20个字符串并用C++向用户显示
- 无论用户输入,我的数组都会接受随机值
- 在 c++ 中处理代码的命令行参数,用于随机输入和用户输入
- 从用户输入的范围中为不同的类创建不同的随机x,y值
- 我如何生成一个随机的小写字符串的长度的用户输入的数字
- 程序如何在重新打开程序后创建文件并知道文件的路径(由用户随机指定)?
- make_heap 在 std::map 上使用用户定义的比较和随机访问迭代器