-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