0

したがって、現在、ユーザー入力によって決定される設定された増分でランダムな文字を生成するこのコードがあります。

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

int sLength = 0;
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";

int stringLength = sizeof(alphanum) - 1;

char genRandom()
{
    return alphanum[rand() % stringLength];
}

int main()
{
    cout << "What is the length of the string you wish to match?" << endl;
    cin >> sLength;
    while(true)
    {
        for (int x = 0; x < sLength; x++)
        {
            cout << genRandom();
        }
        cout << endl;
    }

}

最初の (ユーザーが定義した量の) 文字を別の文字列と比較するために使用できる文字列に格納する方法を探しています。どんな助けでも大歓迎です。

4

3 に答える 3

2

追加するだけ

string s(sLength, ' ');

while (true)、変更

cout << genRandom();

s[x] = genRandom();

ループ内で、cout << endl;ステートメントを削除します。文字を に入れることで、すべての印刷が置き換えられsます。

于 2011-02-20T02:51:36.947 に答える
1

さて、これはどうですか?

    std::string s;
    for (int x = 0; x < sLength; x++)
    {
        s.push_back(genRandom());
    }
于 2011-02-20T02:51:56.433 に答える
0
#include<algorithm>
#include<string>
// ...

int main()
{
    srand(time(0));  // forget me not
    while(true) {
        cout << "What is the length of the string you wish to match?" << endl;
        cin >> sLength;
        string r(sLength, ' ');
        generate(r.begin(), r.end(), genRandom);
        cout << r << endl;
    }

}
于 2011-02-20T03:15:11.837 に答える