gpt4 book ai didi

c - 在 C 中对命令行参数进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 08:14:08 25 4
gpt4 key购买 nike

我需要创建一个程序来对命令行字符串进行排序。 (代码下的示例输出)这是我到目前为止的代码:

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

int stringcomp (const void * x, const void * y);

int main(int argc, char *argv[]){
int i,j;
int k = 1;
char strings[argc-1][20];

strcpy(strings[0], argv[1]);
for(i=2; i< argc-1; i++){
strcat(strings[k],argv[i]);
k++;
}
qsort(strings, argc, 20, stringcomp);
for(j=0 ; j < argc-1; j++){
printf("%s ", strings[j]);
}
return 0;
}

int stringcomp (const void *x, const void *y) {
return (*(char*)x -*(char*)y);
}

这是我在命令行中输入的内容:./inOrder 你好黑暗我的老 friend

这是我应该得到的:黑暗 friend 你好我的老 friend

但这就是我不断得到的:?黑暗?老]@我的

我做错了什么?

最佳答案

继续评论,为了比较字符串和对字符串数组进行排序,您需要处理 2 级间接寻址。所以你的 stringcomp 函数需要看起来像这样:

int stringcomp (const void *x, const void *y) {  
return strcmp (*(char * const *)x, *(char * const *)y);
}

除此之外,为什么不只对指针数组进行排序以按正确顺序对参数进行排序,而不是复制字符串?您只需要如下内容:

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

int stringcomp (const void * x, const void * y);

int main (int argc, char **argv) {

char *strings[argc-1]; /* declare an array of pointers */
int i;

/* assign each argument to a pointer */
for (i = 1; i < argc; i++)
strings[i-1] = argv[i];

/* sort the array of pointers alphabetically with qsort */
qsort (strings, argc - 1, sizeof *strings, stringcomp);

/* output the results */
for (i = 0; i < argc-1; i++)
printf("%s ", strings[i]);

putchar ('\n');

return 0;
}

int stringcomp (const void *x, const void *y) {
return strcmp (*(char * const *)x, *(char * const *)y);
}

示例使用/输出

$ ./bin/sort_argv my dog has fleas
dog fleas has my

仔细阅读,如果您还有其他问题,请告诉我。

关于c - 在 C 中对命令行参数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36829864/

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