2017-02-25 14 views
-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 
+0

您应该通过使用[容器(http://en.cppreference.com/w/cpp/container)如'的std ::矢量'代码更真实的C++,尤其如此。然后你会通过* reference *将这样一个参数传递给你的'bubble_sort'。并用所有警告和调试信息进行编译(例如,[GCC](http://gcc.gnu.org/)的'g ++ -Wall -g' ...)。然后**使用调试器**'gdb' ....顺便说一句,这不是你的作业,所以你的* fix-my-code *问题是离题。 –

+0

不要浪费你的时间泡沫排序。使用'std :: sort'。你的字符串看起来像“12222233 ....”,并且坚持不排序,这需要对现实的一些严重否定。 – user4581301

回答

0

如果从string改变file_contentsstd::vector<string>,你将能够在一个操作就可以了类似于你如何操作普通旧数组的内容。在一个字符串存储所有的数据(如你在代码片断做你贴),使分拣子困难的(不可能的?),因为它其中一个子结束和下一个开始不是很明显的排序算法。