gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:09:42 24 4
gpt4 key购买 nike

我是 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] = '\0';
i++;
}

total = i;

for(i = 0; i < total; ++i){
printf("%s\n", 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;
}

最佳答案

您可能是陈旧 \r\n 的受害者,下面的这个技巧应该会有所帮助

while(fgets(line[i], sizeof(line[i]), plist)) {
line[i][strlen(line[i]) - 1] = '\0';

// 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] = '\0';

i++;
}

关于c - 如何将文件中的字符串列表读取到动态二维数组中,然后在 C 中对其进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59062455/

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