数组随机排序

我有下面的代码,我希望从文件中读取文本,在数组中存储单词,然后以随机顺序打印出来。 最终的数组是int,但应该是char,它不会给我正确的答案。

#include #include #include  #include  int main() { char message[10][150], buffer[150]; int i = 0; int cntr = 9; char freeArray[9]; srand(time(NULL)); freeArray[i] = rand() % cntr; FILE *file_in; file_in = fopen("test.txt", "r"); while (fgets(buffer, 150, file_in)) { i = rand() % cntr; strcpy(message[freeArray[i]], buffer); } while (cntr >= 0) { i = rand() % cntr; strcpy(message[freeArray[i]], buffer); freeArray[i] = freeArray[cntr--]; printf("%s", freeArray[i]); } return 0; } 

我有替代代码,但这个给了我没有随机播放的文本。

 #include #include #include  #include  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; 

 The following code: -- compiles cleanly -- contains all the changes needed to the OPs posted code #include  #include  #include  #include  #define MAX_MESSAGES (10) #define MAX_MESSAGE_LEN (150) static char message[MAX_MESSAGES][MAX_MESSAGE_LEN] = {{'\0'}}; static char buffer[MAX_MESSAGE_LEN] = {'\0'}; int main() { /*declare and initialise variable*/ int i=0; int j; FILE *file_in; if( NULL == (file_in=fopen("test.txt", "r") ) ) { // then, fopen failed perror( "fopen failed for test.txt" ); exit( EXIT_FAILURE ); } // implied else, fopen successful srand(time(NULL)); /*stores and prints the data from the string*/ while( (i 
 The following is to answer the question given in an answer block #include  #include  #include  //#include  #define MAX_MESSAGES (10) #define MAX_MESSAGE_LEN (150) static char message[MAX_MESSAGES][MAX_MESSAGE_LEN] = {{'\0'}}; static char buffer[MAX_MESSAGE_LEN] = {'\0'}; static char t[MAX_MESSAGE_LEN] = {'\0'}; int main() { /*declare and initialise variable*/ int i=0; int j = 0; FILE *file_in = NULL; if( NULL == (file_in=fopen("test.txt", "r") ) ) { // then, fopen failed perror("fopen for test.txt failed"); exit( EXIT_FAILURE ); } // implied else, fopen successful /*stores, sorts and prints the data from the string*/ i = 0; while( (i<10) && (fgets(buffer,150,file_in)) ) { strcpy(message[i],buffer); i++; } // end while for (i = 1; i < 3; i++) { for (j = 1; j < 3; j++) { if (strcmp(message[j - 1], message[j]) > 0) { strcpy(t, message[j - 1]); strcpy(message[j - 1], message[j]); strcpy(message[j], t); } // end if } // end for } // end for printf("\nStrings in order are : "); for (i = 0; i < 3; i++) { printf("message: %d: %s\n", i+1, message[j]); } // end for getchar(); return 0; } // end function: main