String Subscript Out Of Range

I'm trying to create an XOR encrypter with a one time pad. I can't seem to get my randKey function to work as it always outputs an error (mentioned in the title).
http://puu.sh/kKNys/e792e61745.png

Snippet of full code:
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
#include <iostream>
#include <string>
#include <ctime>
using std::cout; using std::cin; using std::endl;
using std::string;

string randKey(const size_t len);	//generates a random key

int main()
{
	string str = "Hello World!";
	string key = randKey(str.length());

	cout << "Key: " << key << endl;
}

string randKey(const size_t len)
{
	srand(time(NULL));
	const char alpha[] = {'a', 'b', 'c', 'd','e','f','g', 'h', 'i', 'j', 'k', 'l', 'm', 
						'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
	//char* key = new char[len + 1];
	string key = "";
	for (size_t i = 0; i < len; i++)
		key[i] = alpha[rand() % 26];

	return key;
}


I've tried allocating memory on the heap and I don't get the error anymore. However, whenever I print it out the last characters are just junk.

Key: ayeozhfffwhmヘBト
Last edited on
Line 23 creates a string of length 0.

Lines 24 and 25 attempt to write to elements of that string that do not exist.

1
2
3
4
    string key;
    for (size_t i=0; i< len; ++i)
        key += alpha[rand()%26];
    return key;
Oh I see. Thanks :)
Topic archived. No new replies allowed.