Hi,

I need to read text from file and then as outcome show separate words, but shuffled. I tried few codes but non of these works for me. I'm getting output, but it do not shows words, but some signs only. I'm posting both codes..

#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    /*declare and initialise variable*/
    char message[5][20],buffer[20],t[20];
    int i=0;
    int j;
    FILE *file_in;
    file_in=fopen("test.txt", "r");
    /*stores and prints the data from the string*/
    while(fgets(buffer,150,file_in)){
        strcpy(message[i],buffer);
    }
   for (i = 1; i < 5; i++) {
      for (j = 1; j < 5; j++) {
         if (strcmp(message[j - 1], message[j]) > 0) {
            strcpy(t, message[j - 1]);
            strcpy(message[j - 1], message[j]);
            strcpy(message[j], t);
         }
      }
   }
printf("\nStrings in order are : ");
   for (i = 0; i < 5; i++)
      printf("%s", message[i]);

   getchar();
    return 0;
}



#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
    /*declare and initialise variable*/
    char message[10][150],buffer[150];
    int i=0;
    int j;
    srand(time(NULL));
    FILE *file_in;
    file_in=fopen("test.txt", "r");
    /*stores and prints the data from the string*/
    while(fgets(buffer,150,file_in)){
        strcpy(message[i],buffer);

    }
    while(i < 10)
{
  j = rand() % 10;
  printf("%s\n",message[j]);
  i++;
}

    return 0;

Have you tried using qsort(). It was made for this, unless your professor wants you to implement your own sorting routine.

I found how to describe this function, but i do not understand how to implement it in my code.

#include <stdlib.h>

/* Arrange the N elements of ARRAY in random order.
   Only effective if N is much smaller than RAND_MAX;
   if this may not be the case, use a better random
   number generator. */
void shuffle(int *array, size_t n)
{
    if (n > 1) {
        size_t i;
    for (i = 0; i < n - 1; i++) {
      size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
      int t = array[j];
      array[j] = array[i];
      array[i] = t;
    }
    }
}

I hesitate to link to another site for your answer, but your question about how to use qsort() is entirely answered in the FAQ here. It explains how qsort() works and gives an example of randomizing data with it. That comparison function is the key to making it work.

Hope this helps.

Do you want to sort or random shuffle your array?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.