读取和组织文件行c++

Reading and organizing file lines C++

本文关键字:c++ 文件 读取      更新时间:2023-10-16

我最近开始使用文件,在我的主要大学项目中我遇到了一些麻烦。

下面的代码计算键入数字并按回车所花费的时间,并将用户的姓名、性别和时间写入文件:

#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. John M 1.449s
  2. Liz F 1.552
  3. Elias M 1.788s

新时间:Albert M 1.522s

"Times.txt" -已更新

  1. John M 1.449s
  2. Albert M 1.522s
  3. Liz F 1.552
  4. Elias M 1.788s

2)"Times.txt"

  1. John M 1.449s
  2. Albert M 1.522s
  3. Liz F 1.552
  4. Elias M 1.788s
  5. Rob M 1.819s
  6. Joe M 1.842
  7. Ash M 1.893s
  8. Sansa F 2.108s
  9. Snow M 2.134s
  10. Andy M 2.333s

新时间:Ana F 1.799s

"Times.txt" -已更新

  1. John M 1.449s
  2. Albert M 1.522s
  3. Liz F 1.552
  4. Elias M 1.788s
  5. Ana F 1.799s
  6. Rob M 1.819s
  7. Joe M 1.842
  8. Ash M 1.893s
  9. Sansa F 2.108s
  10. Snow M 2.134s

可能的解决方案:我想过每次移动到数组位置,并在数组中对它们进行排序,然后重写文件。问题是,我不知道如何以那种方式操作代码。如有任何帮助,不胜感激。

*注意:文件不应该在名称

之前显示位置的数字

我建议你使用一个结构:

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;
};

现在你可以创建vector来保存所有的名字:

std::vector<Entry> students;

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

如果你聪明的话,你会研究如何将矢量写入文件,而不是在这里发布。(提示:这个问题在StackOverflow上已经回答过好几次了)