c语言实现输入一组字符串,为字符串数组并且排序后输出,

#include <iostream>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
using namespace std;
void printArray(char **buff,int len);
void sortBuff(char **buff,int len);
int main(){
    int N,m=0;
    scanf("%d",&N);
    for(int i=0;i<N;i++){//n组数据
        scanf("%d",&m);
        char **a = (char **)malloc(m * sizeof (char *));
        getchar();
        for(int i=0;i<m;i++){;
            a[i] = (char *)malloc(100 * sizeof (char));
            scanf("%s", a[i]);
        }
        printf("\n排序前\n");
        printArray(a, m);
        printf("\n排序后\n");
        sortBuff(a,m);
        printArray(a, m);

    }

}

void printArray(char **buff, int len){//打印函数
    int i;
    for (i = 0; i < len; ++i){
        printf("%s ", buff[i]);
    }
}

void sortBuff(char **buff,int len){//排序
    char *temp;
    int i, j;
    for (i = 0; i < len; ++i){
        for (j = i + 1; j < len; ++j){
            if( strcmp(buff[i], buff[j]) > 0){
                temp = buff[i];
                buff[i] = buff[j];
                buff[j] = temp;
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Cinderella___/article/details/80385700