簡體   English   中英

來自txt文件的C ++插入排序

[英]C++ insertion sort from a txt file

我必須從.txt文件中讀取內容,並使用其他.txt文件將其讀出。 我必須使用插入排序才能根據兩個數字對它們進行排序。 我只能走這么遠,我不知道該如何在有兩個數字進行排序的程序中進行插入排序。

這是我的代碼:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(void)
{
    int serialno[100], suratno[100], ayatno[100];
    string order;

    string str;
    char ch;
    int i = 0;
    int j, temp;

    ifstream fin;
    fin.open("text.txt");

    if(!fin)
    {
        cout << "Cannot open file \'text.txt\'! Quitting.\n";
        exit(0);
    }

    while(fin)
    {

        fin.get(ch); //gets .

        getline(fin, order, '('); //allegedly it removes the delimiter char from stream too

        fin >> suratno;
        fin.get(ch); //gets :
        fin >> ayatno;
        fin.get(ch); //gets )
        fin.get(ch); //gets \n

        cout << serialno << "." << order << "("<<suratno<<":<<ayatno<<")\n";
    }

    fin.close();

    //sort algorithm            
    for (int i = 0; i < length; i++){
        j = i;

        while (j > 0 && suratno [j] < suratno [j-1]){
              temp = suratno [j];
              suratno [j] = suratno [j-1];
              suratno [j-1] = temp;
              j--;
              cout << serialno << endl;
              }
        }
    }

    ofstream fout;
    fout.open("newtext.txt");

    if(!fout)
    {
        cout << "Cannot open output file\'orderedquranorders.txt\'!Quitting.\n";
        exit(0);
    }

    i = 0;
    //write sorted list to output file

    fout.close();

    cout << i << " orders successfully sorted and written.\n";
}

這是文本文件(應使用括號中的數字,首先使用在冒號之前的數字,然后使用在冒號之后的數字):

1. Do not be rude in speech (3:159) 
2. Restrain Anger (3:134)
3. Be good to others (4:36)
4. Do not be arrogant (7:13)
5. Forgive others for their mistakes (7:199)
6. Speak to people mildly (20:44)
7. Lower your voice (31:19)
8. Do not ridicule others (49:11)
9. Be dutiful to parents(17:23)

當前輸出:

  1. 不要言辭粗魯(3:159)
  2. 抑制憤怒(3:134)
  3. 對他人好(4:36)
  4. 孝敬父母(17:23)

預期輸出:

  1. 抑制憤怒(3:134)
  2. 不要言辭粗魯(3:159)
  3. 對他人好(4:36)
  4. 孝敬父母(17:23)

按數字和序列號排序不相同

為了比較兩個數字,可以進行如下比較:

 if(suratno[i] < suratno[i-1] || (suratno[i] == suratno[i-1] && ayatno[i] < ayatno[i-1])){
    /* swap */
 }

或者,您可以使用一個表達式: expr = suratno * 10000 + ayatno 並做一個比較:

 if(expr[i] < expr[i-1]){
    /* swap */
 }

另外,我對您的算法/代碼有一些觀察:

  • 不要using namespace std 特別是在大型程序中,因為它可能導致難以理解的錯誤(請參見此處的示例)。 而是使用using std::<name>當你想避免std:: 防爆。 using std::string 通常,避免using namespace xxxx
  • 我看到您確實手動解析了輸入行,我更喜歡使用正則表達式,它的功能更強大,但需要一些學習。
  • 當需要編寫錯誤消息時,請始終在C ++中寫入stderr流cerr
  • 在排序算法中,最好從1開始而不是0,因為第一項沒有與之比較的上一項。
  • 最后,可以使用現有的C ++函數完成交換。

這是重組后的代碼,並使用了正則表達式,我盡力解釋了這些內容:

#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <vector>
#include <algorithm>

using std::string;

struct Line {
    int expr;   // Expression used to compare
    string text;    // Original line without initial number
};

int main() {
    std::regex linePattern(
        "\\d+"      // 1 or more digits
        "\\. "      // '. ' (dot followed by 1 space)
        "("         // begin char group #1
           ".*"     // zero or more chars
           "\\("    // '(' (left parenthesis)
           "(\\d+)" // char group #2 (suratno: 1+ digits)
           ":"      // ':' (colon)
           "(\\d+)" // char group #3 (ayatno: 1+ digits)
           "\\)"    // ')' (right parenthesis)
        ")"         // end char group #1
    );
    std::smatch groups;         // Regular expression found char groups
    std::vector<Line> lines;    // Vector to store the readed lines

    // Read lines parsing content
    std::ifstream fin("text.txt");
    if(!fin){
        std::cerr << "Cannot open file 'text.txt'! Quitting.\n";
        return 1;
    }
    string line;
    while (std::getline(fin, line))
        if (std::regex_search(line, groups, linePattern) && groups.size() > 0) {
            int suratno = std::stoi(groups[2]);
            int ayatno = std::stoi(groups[3]);
            int compExpr = suratno * 10000 + ayatno; // assumes ayatno < 10,000
            lines.push_back({ compExpr, groups[1] });
        }
    fin.close();

    // sort algorithm (better start in 1)
    for (size_t i = 1; i < lines.size(); i++)
        for (size_t j = i; j > 0 && lines[j].expr < lines[j - 1].expr; j--)
            std::swap(lines[j], lines[j - 1]);

    std::ofstream fout("newtext.txt");
    if(!fout){
        std::cerr << "Cannot open output file 'orderedquranorders.txt'! Quitting.\n";
        return 1;
    }
    for (size_t i = 0; i < lines.size(); i++)
        fout << i + 1 << ". " << lines[i].text << std::endl;
    fout.close();

    std::cout << lines.size() << " orders successfully sorted and written.\n";
    return 0;
}

注意:正則表達式實際上是一個字符串"\\\\d+\\\\. (.*\\\\((\\\\d+):(\\\\d+)\\\\))" ,我使用了C / C ++功能,可將字符串分隔開在編譯之前按空格隔開,因此編譯器只能看到一個字符串。

不要忘記使用-std=c++11選項進行編譯。

using namespace std; 被認為是不良做法,有時可能很危險。 檢查一下

這是您的解決方案:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    int suratno[100], ayatno[100];
    std::string order[100];

    char ch;
    int count = 0;
    int tempInt;
    std::string tempStr;

    std::ifstream fin;
    fin.open("text.txt");

    if (!fin)
    {
        std::cout << "Cannot open file \'text.txt\'! Quitting.\n";
        exit(0);
    }
    else
    {
        while (fin)
        {
            fin.get(ch); //gets the numbers
            fin.get(ch); //gets .

            getline(fin, order[count], '('); //allegedly it removes the delimiter char from stream too

            fin >> suratno[count];
            fin.get(ch); //gets :
            fin >> ayatno[count];
            fin.get(ch); //gets )
            fin.get(ch); //gets \n

            std::cout << count + 1 << "." << order[count] << "(" << suratno[count] << ":" << ayatno[count] << ")\n";
            count++;
        }
    }
    fin.close();
    std::cout << std::endl;

    // sort algorithm (we must sort two times)
    for (int i = 0; i < count; i++)
    {
        for (int j = i; j > 0 && suratno[j] < suratno[j - 1]; j--)
        {
            tempInt = suratno[j];
            suratno[j] = suratno[j - 1];
            suratno[j - 1] = tempInt;

            tempInt = ayatno[j];
            ayatno[j] = ayatno[j - 1];
            ayatno[j - 1] = tempInt;

            tempStr = order[j];
            order[j] = order[j - 1];
            order[j - 1] = tempStr;
        }
    }

    for (int i = 0; i < count; i++)
    {
        for (int j = i; j > 0 && suratno[j] == suratno[j - 1] && ayatno[j] < ayatno[j - 1]; j--)
        {
            tempInt = ayatno[j];
            ayatno[j] = ayatno[j - 1];
            ayatno[j - 1] = tempInt;

            tempInt = suratno[j];
            suratno[j] = suratno[j - 1];
            suratno[j - 1] = tempInt;

            tempStr = order[j];
            order[j] = order[j - 1];
            order[j - 1] = tempStr;
        }       
    }

    // print the sorted list just to check
    for (int i = 0; i < count; i++)
    {
        std::cout << i + 1 << "." << order[i] << "(" << suratno[i] << ":" << ayatno[i] << ")\n";
    }

    // write sorted list to output file
    std::ofstream fout;
    fout.open("newtext.txt");

    if (!fout)
    {
        std::cout << "Cannot open output file\'orderedquranorders.txt\'!Quitting.\n";
        exit(0);
    }
    else
    {
        for (int i = 0; i < count; i++)
        {
            fout << i + 1 << "." << order[i] << "(" << suratno[i] << ":" << ayatno[i] << ")\n";
        }
    }
    fout.close();

    std::cout << std::endl;
    std::cout << count << " orders successfully sorted and written.\n";

    return 0;
}

暫無
暫無

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

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