我必须从一个.txt文件中读取并使用不同的.txt文件进行读取。我必须使用插入排序,以便根据两个数字对它们进行排序。我只能得到这一点,我不知道如何在这个程序中做插入排序,我有两个数字来排序。从txt文件中进行C++插入排序
这里是我的代码:
#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)
电流输出:
- 不要在语音粗鲁(3:159)
- 眕(3:134)
- 要对别人好(4:36)
- 要孝顺父母(17:23)
预期输出:
- 眕( 3:134)
- 不要在言语粗鲁(3:159)
- 要对别人好(4:36)
- 要孝顺父母(17:23)
在数量和序列号两方面进行排序保持不变
去阅读帮助中心的“如何提出一个很好的问题。”另请阅读Eric Lippert的[如何调试小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。你目前有一个巨大的主要功能。至少将其分为三个功能:读取输入,对数据进行排序,写入输出。然后,您可以在开始测试排序之前测试“读取输入”和“写入输出”。 –
@MartinBonner我有一个txt文件我必须阅读,它需要排序。 (3:159)“这些数字在括号内” 2.抑制愤怒(3:134) 3.对别人好(4:36) –
@YSC有什么建议吗? –