About sorting C language strings

Asked 1 years ago, Updated 1 years ago, 214 views

Regarding the problem below, I was able to print the file, but I didn't know how to sort it out, so I got stuck.
Could someone please tell me?

#include<stdio.h>

void main()
{
    inti,n;
    intsin[9][6];
    FILE*fp;

    fp = fopen("before_sort2.txt", "r");

    for(i=0;i<9;i++){
        fscanf(fp, "%s", &(sin[i])));
    }

    fclose(fp);

    for(i=0;i<9;i++){
        printf("%s\n", sin[i]);
    }
}

Example)

AAA
CCC
BBB
III.
DDD
HHH
FFF Corporation
EEE
GGG

Example) Enter ASC

AAA
BBB
CCC
DDD
EEE
FFF Corporation
GGG
HHH
III.

Example) Enter DESC

III
HHH
GGG
FFF Corporation
EEE
DDD
CCC
BBB
AAA

★Point 01 Be aware of the difference between characters and strings
       This time you need to store multiple strings (multiple lines)
★What is the unit of points 021bit, 1 byte?
       What type of int or char type do you often use in programs?
       Check the size of function to see what's going on in your development environment

c

2022-11-08 04:20

1 Answers

I think it's better to have an answer from a SO perspective, so I'll give you an answer that doesn't deliberately meet the theme

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

char data[9][6] = {
    "YZ."
    "DEF",
    "PQR",
    "STU",
    "MNO",
    "ABC",
    "VWX",
    "GHI",
    "JKL",
};
    
void printdata(){
    for(inti=0;i<9;++i){
        printf("%s\n", data[i]);
    }
    printf("\n");
}

int descending_compare(const void*lh, const void*rh){
    return-strcmp(lh,rh);
}
int main(intargc, char*argv[]){
    printdata();
    qsort(data,9,6,strcmp);
    printdata();
    qsort(data,9,6, descending_compare);
    printdata();
}

Challenge from Oira 1. Try actually compiling and executing
Challenge 2. Understand why this is the sort of string and explain it to SO readers
Challenge 3. This code deliberately contains some points that should be fixed, so try to correct them


2022-11-08 09:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.