Converting an array of a fixed size to a string

Hi, I'm just trying to do some type conversion. In Python or JavaScript, it's as easy as calling str() on your object.

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int GenChar()
{

    std::string P;
    srand (time(nullptr));
    int i;

    int arr[i];
    const std::string characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    for (int i = 1; i <=4; i++) {
        arr[i] = rand() % 26;
        std::cout << characters[arr[i]] << std::endl;

    }
    
};


I want to store the contents of arr in a string, P. How should I approach this?

The string, on execution, should be a "randomly" generated string of 4 uppercase characters.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;


string randWord( int L )
{
   const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   string word;
   for ( int i = 1; i <= L; i++ ) word += alphabet[rand()%26];
   return word;
}


int main()
{
   srand( time( 0 ) );
   const int N = 10;
   cout << N << " random four-letter words (ahem) are:\n";
   for ( int i = 0; i < N; i++ ) cout << randWord( 4 ) << '\n';
}
10 random four-letter words (ahem) are:
XYNJ
TQNX
JLND
TQXB
STIA
ZUKP
JECF
FTVV
DAIM
NQZA

Last edited on
Slightly different approach:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

string RandomString(int length)
{
  string res;

  for (int i = 0; i < length; i++)
  {
    res += 'A' + (rand() % 26);
  }

  return res;
}

int main()
{
  srand((unsigned)time(nullptr));
  for (int i = 0; i < 10; i++)
  {
    cout << RandomString(4) << "\n";
  }
}
Thomas, I like that a lot. Can you explain the following line of code to me?

res += 'A' + (rand() % 26);

How does the machine know to continue the sequence of the alphabet?

Then, if I assigned the value of RandomString() to a variable, say P, like so:

P = RandomString(4);

How can I pass P to a new function, CrackP()?

I tried using CrackP(P), but my program can't resolve the type. I then tried returning P at the end of main, also to no avail.

How can I pass the value of P to other functions as a parameter?

Sorry for the silly questions. New to C++.

Thomas, I like that a lot. Can you explain the following line of code to me?
res += 'A' + (rand() % 26);


'A' is sth. like 65 on most char sets. 'B' is 66 and so on. rand() % 26 will generate a number between 0 and 25.

+= append the character to the string - same as res = res + (rand() % 26);
% is the modulo operator

RandomString will return a string so your Crack function needs to accept a string as parameter.

1
2
3
4
5
6
7
8
string str = RandonString(4);

void Crack(string s);
{
  // some code here
}

Call it Crack(str);

Topic archived. No new replies allowed.