something wrong with the output

I'm solving a problem that make me generate a password depends on some rules,

1-the length of the password must be equal to n,
2-the password should consist only of lowercase Latin letters,
3-the number of distinct symbols in the password must be equal to k,
4-any two consecutive symbols in the password must be distinct.

and i wrote the algorithm, but when i put the input (n=5,k=2)
the output must be "ababa" but i get "abab" and the last character is strange
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
#include <iostream>
#include <string>
#include <cstring>

using namespace std;
int main()
{
    char arr[26]={'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 allow[26];
    int n,k,m=0;
    string pass="";
    cin >> n >> k;

    for (int i=0;i<k;i++){
        pass+=arr[j];
        allow[i]=arr[j++];

    }
    for (int i=0;i<n-k;i++){

        if (m==strlen(allow)){
            m=0;
        }
        else{
            pass+=allow[m++];
        }
    }
    cout << pass ;

    return 0;
}
Declare and initialise j.

strlen(allow) can be replaced by k.

Remove lines 24 and 26.
Thanks man,it worked
but can you tell me why strlen() function didn't work !
strlen() relies on the string being null-terminated and you don't explicitly do that. I suspect it comes down to undefined behaviour, as the characters in allow[] aren't set on declaration in line 9. It is just plausible that they might initially be \0, in which case your code might fortuitously run, but don't rely on it.
Topic archived. No new replies allowed.