如何将字符串列表从文件读取到动态二维数组中,然后在 C 中对其进行排序



我是 C 语言的新手,很难将名称文件读取到二维数组中然后进行排序。我想我应该使用 malloc,但我不太确定我是否必须这样做。以下是我现在拥有的代码,它读取文件并将其打印出来,但是当我对其进行排序时,它只对一个名称进行排序,并添加了一些额外的字符。如果我能得到帮助,我将不胜感激。

该文件只包含一个名称列表,例如:
约翰·
亚历克斯
·乔治
·比斯利

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 128 
#define TOT 10 
void selectionSort_str(char arr[][MAX_LEN], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray 
char minStr[MAX_LEN];
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array 
int min_idx = i;
strcpy(minStr, arr[i]);
for (j = i+1; j < n; j++)
{
// If min is greater than arr[j] 
if (strcmp(minStr, arr[j]) > 0)
{
// Make arr[j] as minStr and update min_idx 
strcpy(minStr, arr[j]);
min_idx = j;
}
}
// Swap the found minimum element with the first element 
if (min_idx != i)
{
char temp[MAX_LEN];
strcpy(temp, arr[i]); //swap item[pos] and item[i] 
strcpy(arr[i], arr[min_idx]);
strcpy(arr[min_idx], temp);
}
}
}

int main(void) {
char line[TOT][MAX_LEN];
FILE *plist = NULL; 
int i = 0;
int total = 0;
int k = sizeof(line)/sizeof(line[0]);
plist = fopen("plist1.txt", "r");
while(fgets(line[i], MAX_LEN, plist)) {
line[i][strlen(line[i]) - 1] = '';
i++;
}
total = i;
for(i = 0; i < total; ++i){
printf("%sn", line[i]);
}
//sort strings
selectionSort_str(line, k);
printf("*****Sorted array is: n"); 
for(i = 0; i < k; i++)
{
printf("%s ", line[i]);
}    

return 0;
}

您可能是陈旧rn的受害者,下面的这个黑客应该会有所帮助

while(fgets(line[i], sizeof(line[i]), plist)) {
line[i][strlen(line[i]) - 1] = '';
// these stale '/r' s when used in strcmp will give unwanted results
// so strip those aswell..
if( line[i][strlen(line[i]) - 1] == 'r' )
line[i][strlen(line[i]) - 1] = '';
i++;
}

最新更新