簡體   English   中英

如何將 txt 文件讀入數組並按升序排序?

[英]How can I read a txt file to an array and sorting in ascending order?

我有一個 txt 文件,其中包含 10000 個密碼。我正在嘗試按長度對密碼進行排序。這是我的 function:

void bubbleSortASC(){
    int n = 9999;
    int i,j ;
    char pw[n];
    char temp;
    FILE* fp;
    fp = fopen("C:\\Users\\inanm\\Desktop\\project-work-2018555459\\10-million-password-list-top\\10000.txt", "r");
    //fgets(pw, n , fp);
    while(!feof(fp)){
        fgets(pw, n , fp);
       //printf("%s",pw);
    }
    for(i = 0; i < n-1;i++) {
        for(j = i+1; j < n; j++){
            if(strlen(pw[i]) > strlen(pw[j])){
                strcpy(temp,pw[i]);
                strcpy(pw[i],pw[j]);
                strcpy(pw[j],temp);
            }
        }
    }
    fclose(fp);
printf("Ascending order of first 10 passwords are : \n");
for (i = 0; i < 10; i++){
        printf("%s ", pw[i]);
    }
     printf("\n");
        
}

我沒有錯誤,但我的 output 是空的。你能幫我找到問題嗎

這會做


void bubbleSortASC() {
    const int lines = 9999;     //< number of words in the file
    const int max_width = 128;  //< max width of a word

    char pw[lines][max_width];  //< array of words

    FILE* fp;
    fp = fopen("words.txt", "r");
    int curr = 0;
    while (!feof(fp)) {
        fgets(pw[curr++], max_width, fp);
    }
    fclose(fp);

    char* sorted[lines];        //< array of char* will be in a sorted order
    for (int i = 0; i < lines; i++) sorted[i] = pw[i];

    // the bubble sort
    for (int i = 0; i < lines - 1; i++) {
        for (int j = 0; j < lines - i - 1; j++) {
            if (strlen(sorted[j]) > strlen(sorted[j+1])) {
                char* tmp = sorted[j];
                sorted[j] = sorted[j+1];
                sorted[j+1] = tmp;
            }
        }
    }

    printf("Ascending order of first 10 passwords are : \n");
    for (int i = 0; i < 10; i++) {
        printf("%s", sorted[i]);
    }
    printf("\n");

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM