mardi 15 décembre 2015

Printing chars for a randomly generated string C/C++, Chars not in the random list are being also printed

I'm trying to accomplish some things in C++ (beginner stuff mind you) and I've run into a problem. I'm trying to generate a random string with letter upper/lowercase a-z, numbers and a space. As you can see from the code I have created another string that holds those symbols and with rand() % size I'm assigning a random char to the new string. The problem here is that when printing the string on the console I see other symbols such as "?, !, -, =, ." and others. Why is that?

int fillRandomlyStr(char * str, unsigned len) {
    char symbols [] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ";
    unsigned length = strlen(symbols);
    for (unsigned i = 0; i < len; i++) {
        str[i] = symbols[rand() % length];  
    }
    std::cout << "Отпечатване на низ със случайно генерирани символи: \n" << str << std::endl;
    //Printing a string with randomly generated chars
    return 0;
}

Earlier I did something similar replacing vowels in a string with consonants and it worked fine. Here it is:

int replaceVowels(char * str) {
    const char letters [] = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ";
    unsigned len = strlen(str);
    for (unsigned i = 0; i < len; i++)
    {
        switch (str[i])
        {
            case 'a': str[i] = letters[rand() % 40];
            case 'A': str[i] = letters[rand() % 40];
            case 'o': str[i] = letters[rand() % 40];
            case 'O': str[i] = letters[rand() % 40];
            case 'e': str[i] = letters[rand() % 40];
            case 'E': str[i] = letters[rand() % 40];
            case 'i': str[i] = letters[rand() % 40];
            case 'I': str[i] = letters[rand() % 40];
            case 'y': str[i] = letters[rand() % 40];
            case 'Y': str[i] = letters[rand() % 40];
            case 'u': str[i] = letters[rand() % 40];
            case 'U': str[i] = letters[rand() % 40];
        }
    }
    std::cout << "Заменени всички гласни в низа с произволни съгласни: \n" << str << std::endl; //Printing it out
    return 0;
}

So why does this problem when generating the random string appear? I would appreciate the help.




Aucun commentaire:

Enregistrer un commentaire