读取和组织文件行c++
Reading and organizing file lines 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"
- John M 1.449s
- Liz F 1.552
- Elias M 1.788s
新时间:Albert M 1.522s
"Times.txt" -已更新
- John M 1.449s
- Albert M 1.522s
- Liz F 1.552
- Elias M 1.788s
2)"Times.txt"
- John M 1.449s
- Albert M 1.522s
- Liz F 1.552
- Elias M 1.788s
- Rob M 1.819s
- Joe M 1.842
- Ash M 1.893s
- Sansa F 2.108s
- Snow M 2.134s
- Andy M 2.333s
新时间:Ana F 1.799s
"Times.txt" -已更新
- John M 1.449s
- Albert M 1.522s
- Liz F 1.552
- Elias M 1.788s
- Ana F 1.799s
- Rob M 1.819s
- Joe M 1.842
- Ash M 1.893s
- Sansa F 2.108s
- 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上已经回答过好几次了)
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到