vendredi 18 novembre 2016

Inputing string and printing them in random order

im having a little trouble getting my words to print out in random order. The 8 words that i insert will need to be printed out in random order. Right now im only able to generate a few of them in random order because it overwrites the previous space if the same number is generated twice. How can i eliminate this issue?

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    #include <ctype.h>
    #define MAX 50

    int readLine(char string[]);

    int main(void)
    {
        int i;
        char str[8][MAX], temp[8][MAX];
        srand((unsigned)time(NULL));
        int r_num;

        printf("Enter 8 words:\n");

        for(i=0; i<8; ++i)
        {
            readLine(str[i]);
        }


        for (int i = 0; i < 8; i++)
        {
            r_num = rand()%8+1;
            strcpy(temp[r_num], str[i]);
        }

    printf("\nRandom order of words: \n");
    for(i=0; i<8; ++i)
    {
        printf("%s\n", temp[i]);
    }
    printf("\n");

    return 0;
}

int readLine(char string[])
{
    int ch;
    int i=0;
    while (isspace(ch = getchar()))
        ;
    while (ch != '\n' && ch != EOF)
    {
        if (i < MAX)
        {
            string[i++] = ch;
            ch = getchar();
        }
    }
    string[i] = '\0';
    return i;
}




Aucun commentaire:

Enregistrer un commentaire