根据用户输入生成随机字母

时间:2017-10-06 20:10:39

标签: c++

我必须做一个简单的猜字游戏。到目前为止,我已经完成了几乎所有的事情,但是我不确定在完成一项任务时该怎么做。 所以在比赛开始之前,它要求用户输入两件事:

  

输入不同字符的数量:(如果输入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;
}

1 个答案:

答案 0 :(得分:0)

只需将您的发电机线更改为:

uniform_int_distribution<char> dis{'A', 'A' + amount - 1};

我还建议事先添加一些验证,例如:

if (amount < 1 || amount > 26) {
    cout << "Bad amount" << endl;
    // exit or something
}