-1
我需要创建一个程序,读取一个文本文件,并显示其内容。我只能让我的程序读取文本文件。但是,我不知道如何调用我的函数来排序文件。有没有办法将其内容变成一个字符串为我的函数进行排序?试图冒泡排序的文本文件在C++
这是我的计划:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void bubble_sort(string arr[], int length)
{
string temp;
int iteration;
int index;
for (iteration=0; iteration<length; iteration++)
{
for (index=0; index<length-iteration; index++)
{
if (arr[index].compare(arr[index+1]) != 0)
{
temp = arr[index];
arr[index] = arr[index+1];
arr[index+1] = temp;
}
}
}
}
int main(void)
{
ifstream file("list.txt");
string str;
string file_contents;
while (getline(file, str))
{
file_contents += str;
file_contents.push_back('\n');
}
cout << file_contents;
return(0);
}
这是文本文件:
2 Witcher CdProjectRed 2015 9.3
4 Assassin Ubisoft 2013 8.3
5 Dragon Age Bioware 2014 8.5
3 Mass Effect Bioware 2013 8.9
1 Doom IDsoftware 2016 8.5
您应该通过使用[容器(http://en.cppreference.com/w/cpp/container)如'的std ::矢量'代码更真实的C++,尤其如此。然后你会通过* reference *将这样一个参数传递给你的'bubble_sort'。并用所有警告和调试信息进行编译(例如,[GCC](http://gcc.gnu.org/)的'g ++ -Wall -g' ...)。然后**使用调试器**'gdb' ....顺便说一句,这不是你的作业,所以你的* fix-my-code *问题是离题。 –
不要浪费你的时间泡沫排序。使用'std :: sort'。你的字符串看起来像“12222233 ....”,并且坚持不排序,这需要对现实的一些严重否定。 – user4581301