c - 字符串数组随机排序

标签 c arrays string sorting

我有下面的代码,它从文本文件读取并给出输出单词。我怎样才能打乱这些词的顺序?

#include <stdio.h>
#include <string.h>

int main()
{
    /* Declare and initialise variable */
    char message[10][150], buffer[150];
    int i = 0;
    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);
        printf("%s", message[i]);
        i++;
    }

    getchar();
    return 0;
}

最佳答案

您可以使用函数 rand() 从数组消息的随机位置打印每个单词。

char message[10][150], buffer[150];
int position,i=0;
srand(time(NULL));

while (fgets(buffer, 150, file_in)) {

    strcpy(message[i], buffer);

    i++;
}
for(i=0;i<10;i++){
   position = rand() % 10;
   printf("%s", message[position]);
}

或者您可以将它们存储在数组中的随机位置,并使用简单的 for 循环从数组中连续打印数据。

关于c - 字符串数组随机排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27780011/

相关文章:

arrays - 确定数组中是否存在 a、b、c 以使 a+b+c = z 的算法?

C - 无法编辑或打印字符数组

c - 是否有基于 Microsoft C 的列表集合?

c - DevC++ 中未声明“Node”(在此函数中首次使用)

c - 为什么我在左位移的不同实现中有这种不同的行为?

c - 在使用 fgets() 填充后,如何从我的字符串数组中删除换行符 "\n"?

javascript - for() 循环比较两个数组,然后更改另一个数组。仅 JavaScript

c - 如何将字符串拆分为不同的类型(int 表示数值,char 表示字母)?

字符串比较中的C++字符

c++ - 在 C/C++ 或任何其他此类语言中将 & 符号应用于变量或数据类型时返回什么类型的地址?