繁体   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