2013-04-13 85 views
0

我最近開始使用文件,並在我的主要大學項目中遇到了一些麻煩。閱讀和組織文件行C++

下面的代碼時候,你需要多長時間來輸入一個號碼,按下回車鍵,並在文件中寫入用戶的姓名,性別和時間:

#include <iostream> 
#include <ctime> 
#include <fstream> 
#include <string> 

using namespace std; 

int LinesCounter(string filename) 
{ 
    ifstream b_file(filename); 

    // new lines will be skipped unless we stop it from happening:  
    b_file.unsetf(ios_base::skipws); 

    // count the newlines with an algorithm specialized for counting: 
    unsigned line_count = count(
     istream_iterator<char>(b_file), 
     istream_iterator<char>(), 

     '\n'); 

    return line_count; 

} 

int main() 
{ 
     //Starts timing 
    clock_t begin = clock(); 

    int letter; 
    cin>>letter; 
    cin.ignore(); 


    //Obtains the total amount of seconds taken 
    clock_t end = clock(); 
    double elapsed_secs = double(end - begin)/CLOCKS_PER_SEC; 

    cout << "\nCongratulations, you took " <<elapsed_secs <<" seconds." <<endl <<endl; 

    cout<<"Insert your name: "; 
    string name; 
    getline(cin, name); 
    cout<<endl; 

    cout<<"M/F: "; 
    char sex; 
    cin >> sex; 
    cout<<endl; 
    cin.ignore(); 

    int NumberOfLines = LinesCounter("Times.txt"); 

    if (NumberOfLines < 10) 
    { 
     ofstream a_file ("Times.txt", ios::app); 

     a_file<<name <<" " <<sex <<" " <<elapsed_secs <<"s" <<endl; 

     a_file.close(); 
    } 


    cin.get(); 
} 

的代碼應該只存儲10倍( 10行姓名,性別和時間),並根據時間對清單進行整理。這樣,文件的第一行應該有最快的時間(以及相應的用戶名和性別),最後一行是最慢的時間。 實施例:

1) 「Times.txt」

  1. 約翰中號1.449s
  2. 利茲˚F1.552s
  3. Elias的中號1.788s

新時間:阿爾伯特中號1.522s

「Times.txt」 - 已更新

  1. 約翰中號1.449s
  2. 阿爾伯特中號1.522s
  3. 利茲˚F1.552s
  4. Elias的中號1.788s

2) 「Times.txt」

  1. John M 1.449s
  2. Albert M 1.522s
  3. 利茲˚F1.552s
  4. Elias的中號1.788s
  5. 羅布中號1.819s
  6. 喬中號1.842s
  7. 灰中號1.893s
  8. 的Sansa˚F2.108s
  9. 雪中號2.134s
  10. 安迪中號2.333s

新時間:安娜˚F1.799s

「Times.txt」 - 更新

  1. 約翰·中號1.449s
  2. 偉業中號1.522s
  3. 利茲˚F1.552s
  4. 埃利亞斯中號1.788s
  5. 安娜˚F1.799s
  6. Rob M 1.819s
  7. Joe M 1.842s
  8. Ash M 1。893S
  9. 的Sansa˚F2.108s
  10. 雪中號2.134s

可能的解決方案:我考慮每次移動一個數組位置,並在陣列中它們梳理,然後重寫該文件。問題是,我不知道如何以這種方式操縱代碼。任何幫助將不勝感激。

*注:文件是不應該

回答

0

我建議你使用結構的名稱前顯示位置的號碼:

struct Entry 
{ 
    std::string name; 
    unsigned int seconds; 
}; 

現在超載operator <,使排序:

struct Entry 
{ 
    bool operator<(const Entry& e) 
    { 
     if (name == e.name) 
     { 
     return seconds < e.seconds; 
     } 
     else 
     { 
     return name < e.name; 
     } 
    } 
    std::string name; 
    unsigned int seconds; 
}; 

現在您可以創建矢量來保存所有名稱:

std::vector<Entry> students; 

你可以使用向量上的std::sort。 (查找std::sort的語法)。

如果你聰明,你會研究如何寫一個向量到一個文件,而不是張貼在這裏。 (提示:它已經在StackOverflow上多次回答)。