C 从文本文件排序数组
我似乎无法按升序对文本文件进行排序。出于某种原因,它在第一个和第二个条目交换的情况下打印我的洗牌数组。经过数小时的努力,我似乎把自己弄糊涂了,可能犯了一些错误C 从文本文件排序数组,c,C,我似乎无法按升序对文本文件进行排序。出于某种原因,它在第一个和第二个条目交换的情况下打印我的洗牌数组。经过数小时的努力,我似乎把自己弄糊涂了,可能犯了一些错误 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> // Accepts: command line input // Returns: 0 if no error int main(i
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Accepts: command line input
// Returns: 0 if no error
int main(int num_args, char *arg_strings[])
{
int x = 0, i, track_count = 0;
unsigned long Max_Length = 0;
char line[500], *temp;
FILE *file = fopen("playlist.txt", "r");
/* The next line checks if the playlist file exists and if it's not there, "Cannot Open File" is printed to the screen */
if (file == NULL)
{
printf("Cannot open file\n");
}
/* The following code identifies each line in the text and lines are shuffled accordingly */
while (fgets(line, sizeof(line), file) != NULL)
{
track_count++;
if (strlen(line) > Max_Length)
Max_Length = strlen(line);
}
rewind(file);
char *Array[track_count];
while (fgets(line, sizeof(line), file) != NULL)
{
Array[x] = malloc(strlen(line));
if (Array[x] == NULL)
{
printf("A memory error occurred.\n");
return(1);
}
strcpy(Array[x], line);
/* change \n to \0 */
Array[x][strlen(Array[x]) - 1] = '\0';
x++;
}
printf("The original playlist is:\n");
for (x = 0; x < track_count; x++)
printf("%2d %s\n", x, Array[x]);
/* The array will now be shuffled: */
srand((unsigned int)time(NULL));
for (x = track_count - 2; x > 1; x--)
{
while (1)
{
i = rand() % (track_count - 1) + 1;
if (Array[x + 1][0] == Array[i][0])
continue;
if (Array[x - 1][0] == Array[i][0])
continue;
if (Array[i + 1][0] == Array[x][0])
continue;
if (Array[i - 1][0] == Array[x][0])
continue;
temp = Array[x];
Array[x] = Array[i];
Array[i] = temp;
break;
}
}
printf("\nShuffled Array\n");
for (x = 0; x < track_count; x++)
printf("%2d %s\n", x, Array[x]);
/* Sorting */
int m = 0;
int z = 0;
int k = 0;
char j = 0;
char tempArtist[Max_Length][Max_Length];
for (m = 0; m < track_count; m++)
{
for (z = 0; z <track_count - 1 - m; z++)
{
if (strcmp(Array[j], Array[j + 1]) > 0)
{
strcpy(tempArtist, Array[j]);
strcpy(Array[j], Array[j + 1]);
strcpy(Array[j + 1], tempArtist);
}
}
}
puts("");
printf("Sorted Playlist:");
for (k = 0; k <= track_count; k++)
{
printf("\n%s", Array[k]);
}
return 0;
}
#包括
#包括
#包括
#包括
//接受:命令行输入
//如果没有错误,则返回0
int main(int num_args,char*arg_字符串[])
{
int x=0,i,磁道计数=0;
无符号长最大长度=0;
字符行[500],*温度;
FILE*FILE=fopen(“playlist.txt”、“r”);
/*下一行检查播放列表文件是否存在,如果不存在,屏幕上会显示“无法打开文件”*/
if(file==NULL)
{
printf(“无法打开文件\n”);
}
/*下面的代码标识文本中的每一行,并相应地将行洗牌*/
while(fgets(line,sizeof(line),file)!=NULL)
{
轨道计数++;
如果(strlen(线)>最大长度)
最大长度=strlen(直线);
}
倒带(文件);
字符*数组[轨道计数];
while(fgets(line,sizeof(line),file)!=NULL)
{
数组[x]=malloc(strlen(line));
if(数组[x]==NULL)
{
printf(“发生内存错误。\n”);
申报表(1);
}
strcpy(数组[x],行);
/*将\n更改为\0*/
数组[x][strlen(数组[x])-1]='\0';
x++;
}
printf(“原始播放列表为:\n”);
对于(x=0;x