gpt4 book ai didi

c - 字符串数组随机排序

转载 作者:行者123 更新时间:2023-11-30 17:23:01 27 4
gpt4 key购买 nike

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

#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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com