Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was given this code to start:
C++
char s[21];

    for ( k = 0; k < 20; k++ )
        s[k] = ' ';
    s[20] = '\0';

    printf("|%s|\n", s);

I have to include the following into the code i have:
- place 5 random characters within string s
- symbol should be a lowercase character
- location/position must be within valid string

The final code should generate (without the periods, just spaces):
|...................|
|..l..gy..x...c|

the letters and spacing can be random, but must stay within the string

What I have tried:

I haven't been able to get past this:
C++
char s[21];

    for ( k = 0; k < 20; k++ )
        s[k] = ' ';
    s[20] = '\0';

    printf("|%s|\n", s);
    printf("\n");

    return 0;
}

Any help would be appreciated as I really struggle with coding. Thanks!
Posted
Updated 1-Nov-19 23:55pm
v2
Comments
Peter_in_2780 2-Nov-19 0:09am    
Think about how you would do it with pencil and paper.
Note down those steps.
Translate them into code.
Compile and test.

 
Share this answer
 
Start by setting up a char array, which contains the characters you want to choose from. For "all lowercase characters" that would be:
C++
char pickFrom[] = "abcdefghijklmnopqrstuvwxyz";
Then create a random number generator using srand: C library function - rand() - Tutorialspoint[^]
You can now use rand inside a loop to "pick" random characters from the array (using the modulus operator) and set them into your output string.

Give it a try: it's isn't hard to do if you think about it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900