how to set the length of a string

May 9, 2013 at 8:50pm
closed account (9Nh5Djzh)
Hi!
I am making a program that generates a random 10 character length password that should be legible according to English pronunciation laws, but I don't know if I should use a string or a char. So far I have a program that generates a random series of characters, but the output is a bunch of strange characters and I don't know why. Can someone help me?


#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
while (true)
{

unsigned seed = time(0);
srand(seed);
char first[6] = { 'ab', 'ho', 'fr', 'de', 'li', 'me' };
char second[6] = { 'ee', 'ro', 'an', 'so', 'ac', 'lo' };
char third[6] = {'don', 'lut', 'tiv', 'hol', 'gra', 'riz' };
char fourth[6] = {'ers', 'ely', 'ate', 'der', 'phy', 'ing' };
string password;
for (int n = 0; n <= 4; n++)
{
password = password + first[rand() % 25] + second[rand() % 25] + third[rand() % 25] + fourth[rand() % 25];
}


cout << "Your generated password:" << endl;
cout << password << endl;
cin.get();

}
return 0;
}
May 9, 2013 at 9:09pm
http://www.cplusplus.com/articles/z13hAqkS/

char first[6] = { 'ab', 'ho', 'fr', 'de', 'li', 'me' };

Those are actually 6 strings, 12 chars total. Use a string instead.
May 9, 2013 at 9:21pm
char first[6] = { 'ab', 'ho', 'fr', 'de', 'li', 'me' }; none of the syllables is a proper char. So this is your first mistake. If you wish to store more than one character in a variable, use a string, or in this example array of strings:
string first[6] = { "ab", "ho", "fr", "de", "li", "me' }; // note double quotes . (You could use char[][], but why bother?)
Then use your modulo correctly:
first[rand() % 25]; may be equal to e.g. first[20]; (It's a random number between 0 and 24) which is out of bounds of first, so that's where all the junk come to your output from.

Use first[rand() % 6]; instead.
Last edited on May 9, 2013 at 9:25pm
May 9, 2013 at 9:30pm
closed account (9Nh5Djzh)
Thank you both for your help!
One more question: how do I set a length for the string? I want to make it so it's only 10 characters long, and right now it generates a password using 2 of each of the array elements.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
while (true)
{

unsigned seed = time(0);
srand(seed);
string password;
string first[6] = { "ab", "ho", "fr", "de", "li", "me" };
string second[6] = { "ee", "ro", "an", "so", "ac", "lo" };
string third[6] = { "don", "lut", "tiv", "hol", "gra", "riz" };
string fourth[6] = {"ers", "ely", "ate", "der", "phy", "ing" };

for (int n = 0; n <= 1; n++)
{
password = password + first[rand() % 6] + second[rand() % 6] + third[rand() % 6] + fourth[rand() % 6];
}


cout << "Your generated password:" << endl;
cout << password << endl;
cin.get();

}
return 0;
}
May 9, 2013 at 9:36pm
Topic archived. No new replies allowed.