首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从txt文件中C++插入排序

从txt文件中C++插入排序
EN

Stack Overflow用户
提问于 2016-11-29 12:07:26
回答 2查看 2.9K关注 0票数 2

我必须从一个.txt文件中读取,然后用一个不同的.txt文件输出它。我必须使用插入排序,以便根据两个数字对它们进行排序。我只能走这么远,我不知道如何在这个程序中进行插入排序,因为我有两个数字要排序。

这是我的代码:

代码语言:javascript
复制
#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";
}

这是文本文件(应该使用括号中的数字,首先是冒号之前的数字,其次是冒号后面的数字):

代码语言:javascript
复制
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)

按数字和序列no排序,保持不变。

EN

回答 2

Stack Overflow用户

发布于 2016-11-29 23:35:41

为了比较两对数字,您可以进行以下比较:

代码语言:javascript
复制
 if(suratno[i] < suratno[i-1] || (suratno[i] == suratno[i-1] && ayatno[i] < ayatno[i-1])){
    /* swap */
 }

或者可以使用一个表达式:expr = suratno * 10000 + ayatno。只做一个比较:

代码语言:javascript
复制
 if(expr[i] < expr[i-1]){
    /* swap */
 }

另外,我对您的算法/代码有一些观察:

  • 不要使用using namespace std。特别是在大型程序中,因为它会导致模糊的big (参见示例here)。相反,当您想要避免使用using std::<name>时,请使用std::。例如。using std::string。通常,避免使用using namespace xxxx
  • 我看到您确实手动解析了输入行,我更喜欢使用正则表达式,这些表达式更通用,功能更强大,但需要一点学习。
  • 当需要写入错误消息时,请始终在cerr中写入stderr流C++。
  • 在排序算法中,最好从1开始,而不是0,因为第一项没有前一项可与之比较。
  • 最后,可以使用现有的C++函数完成交换。

下面是您的代码重新组织并使用正则表达式,我试图尽可能多地解释这些表达式:

代码语言:javascript
复制
#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选项进行编译。

票数 0
EN

Stack Overflow用户

发布于 2016-11-30 02:10:20

using namespace std;被认为是不好的做法,有时可能是危险的。检查this

以下是您的解决方案:

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40865531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档