我如何生成一个随机的小写字符串的长度的用户输入的数字

how would i generate a random lowercase string the length of the users entered number

本文关键字:字符串 数字 输入 用户 随机 何生成 一个      更新时间:2023-10-16

你好,我试图写一个函数,将生成小写字母的随机字符串。随机字符串的长度将是用户输入的数字。到目前为止我已经讲了这么多,但我相信我把事情复杂化了

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
char randString(){
int number;
     str::string Str; //str has not been declared error
     for(unsigned int i = 0; i <8; i++){
     Str += randString(); //str was not declared in this scope error
     }
     cout << Str << endl; // str was not declared in this scope error
}

int main() {
    char c;
    int number;
    srand (time(0));
    cout << "Enter a number.n"
            "That number will generate a random string of lower case letters the length of the number" << endl;
    cin >> number;
    for (int i=0; i < number; i++){
        number = rand() % 26;
        c = 'a' + number;
        cout << randString();
    }
    return 0;
}

您更改了for循环内的变量number的值,该变量也是循环条件变量。这将导致一个未定义的行为,因为每次执行语句number = rand() % 26;时,number的值都会改变。然而,从我对你的问题陈述的理解来看,我认为这就是你想要达到的目标:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
    int number;
    char c;
    srand(time(NULL));
    cout << "Enter a number.n"
        "That number will generate a random string of lower case letters the length of the number" << endl;
    cin >> number;
    for(int i=0;i<number;i++)
    {
        c = 'a' + rand()%26;
        cout << c;
    }
    return 0;
}

希望这对你有帮助。好运!