Generating random strings

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
27
28
29
30
31
32
33
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <ctime>

using namespace std;

string randstr(int);
int main()
{
	string str;
	int s = 12, p = 5, x[s][p], size;
	
	cout << "\t\t";
	for (int count = 1; count < 6; count++)
	{
		cout << count << "\t";
	}
	
	randstr(4);
	
	
	return 0;
	
}

string randstr(int)
{
	string name;
	name = 65 + rand() % 91;
	return name;
}


I want to generate random strings from A to Z with a specific length of 3 for each generation. For example:

BRC
YUG
YFH

How do I fufill this with the code presented and the function at the bottom?
Thank you !
This looks like it is a school assignment of some sort. I won't solve it for you but I will give you some pointers.

1. First of all, the rand() function is going to return an integer. Not a string. Remember that a string is a set of characters.

2. Because of #1, you will need to generate your string one character at a time. So your randstr function will need to have a loop in it to do this. If you wish, you may also pick the length of the string at random.... not sure if that's what you want.

3. Remember that as directed by line 31, your random number will be divided by 91 and the remainder will be added to 65... so only use 91 if you want the character to be ANY of the 91 characters in the ASCII table after 65. (65 is A)

4. Are you looking to assign the string to a variable upon return from the function?

5. You will get the same string every time if you don't seed the random number generator with the current time first.
Last edited on
Okay i believe I got it. But please, if you can, check back in the next 24 hours if i have any questions about this. Yes it is a school assignment haha. Thanks a lot.
Topic archived. No new replies allowed.