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

时间:2016-10-14 02:57:03

标签: c++

您好我正在尝试编写一个会生成小写字母随机字符串的函数。随机字符串的长度将是用户输入的数字。到目前为止,我有这么多,但我相信我过于复杂化了

#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;
}

1 个答案:

答案 0 :(得分:0)

您在for循环中更改了变量number的值,这也是您的循环条件变量。这将导致未定义的行为,因为每次执行语句number时都会更改number = rand() % 26;的值。但是,根据我的理解阅读你的问题陈述,我认为这是你想要实现的目标:

#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;
}

希望这会有所帮助。祝你好运!