Storing Chars Into Strings in C++

179 views Asked by At

So right now I have this code that generates random letters in set increments determined by user input.

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

}

I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.

3

There are 3 answers

4
Jeremiah Willcock On BEST ANSWER

Just add

string s(sLength, ' ');

before while (true), change

cout << genRandom();

to

s[x] = genRandom();

in your loop, and remove the cout << endl; statement. That will replace all of the printing by putting the characters into s.

0
Johan Kotlinski On

Well, how about this?

    std::string s;
    for (int x = 0; x < sLength; x++)
    {
        s.push_back(genRandom());
    }
0
wilhelmtell On
#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;
    }

}