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.449s
- 利茲˚F1.552s
- Elias的中號1.788s
新時間:阿爾伯特中號1.522s
「Times.txt」 - 已更新
- 約翰中號1.449s
- 阿爾伯特中號1.522s
- 利茲˚F1.552s
- Elias的中號1.788s
2) 「Times.txt」
- John M 1.449s
- Albert M 1.522s
- 利茲˚F1.552s
- Elias的中號1.788s
- 羅布中號1.819s
- 喬中號1.842s
- 灰中號1.893s
- 的Sansa˚F2.108s
- 雪中號2.134s
- 安迪中號2.333s
新時間:安娜˚F1.799s
「Times.txt」 - 更新
- 約翰·中號1.449s
- 偉業中號1.522s
- 利茲˚F1.552s
- 埃利亞斯中號1.788s
- 安娜˚F1.799s
- Rob M 1.819s
- Joe M 1.842s
- Ash M 1。893S
- 的Sansa˚F2.108s
- 雪中號2.134s
可能的解決方案:我考慮每次移動一個數組位置,並在陣列中它們梳理,然後重寫該文件。問題是,我不知道如何以這種方式操縱代碼。任何幫助將不勝感激。
*注:文件是不應該