上一次用到了从c++中输出文本文档,用到了头文件fstream,下面详细介绍一下头文件fstream。
fstream包含三个类,分别是:
ifstream—从已有的文件中读。
ofstream—从已有的文件中写。
fstream—打开文件供读写。
对于这三个类的公共函数可以参考c++ reference。先介绍一部分:
ios::beg 文件头 ios::end 文件尾 ios::cur 当前位置 例子: file.seekg(0,ios::beg); //让文件指针定位到文件开头 file.seekg(0,ios::end); //让文件指针定位到文件末尾 file.seekg(10,ios::cur); //让文件指针从当前位置向文件末方向移动10个字节 file.seekg(-10,ios::cur); //让文件指针从当前位置向文件开始方向移动10个字节 file.seekg(10,ios::beg); //让文件指针定位到离文件开头10个字节的位置
常用的判断错误的方法:
good() 如果文件打开成功
bad() 打开文件时发生错误
eof() 到达文件尾
读取文件:对于程序来说,从外部读取数据吗,因此要定义输入流,即定义输入流对象,这个对象中存放从文件中读入的输入流。
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream infile;
string t1;
string t2;
vector<string> id;
vector<string> time;
infile.open("C:\\Users\\CiCi\\Desktop\\数学建模\\id.txt");
if (!infile.is_open())
cout << "open file failure" << endl;
while (!infile.eof())
{
infile >> t1;
id.push_back(t1);
}
infile.close();
infile.open("C:\\Users\\CiCi\\Desktop\\数学建模\\time.txt");
if (!infile.is_open())
cout << "open file failure" << endl;
while (!infile.eof())
{
infile >> t2;
time.push_back(t2);
}
infile.close();
for (auto it = id.begin(); it != id.end(); it++)
{
id_index.push_back(it - id.begin());
}
for (auto it = time.begin(); it != time.end(); it++)
{
time_index.push_back(it - time.begin());
}
for (auto it = time.begin(); it != time.end(); it++)
{
string t = *it;
if (t.substr(2, 1) != ":")
{
time_h.push_back(atoi(t.substr(0, 1).c_str()));
time_m.push_back(atoi(t.substr(2, 2).c_str()));
}
else
{
time_h.push_back(atoi(t.substr(0, 2).c_str()));
time_m.push_back(atoi(t.substr(3, 2).c_str()));
}
}
for (auto it = time_h.begin(); it != time_h.end(); it++)
{
auto t3 = time_h.at(it - time_h.begin()) * 60 + time_m.at(it - time_h.begin());
time_t.push_back(t3);
}
return 0;
}
PS:这里介绍一个把string型的对象转换为int型的函数atoi。
int atoi(const char*str);
由于所需要的参数是c风格的字符串,所以还需要把string对象转换为c中的字符串样式。在c语言中没有string类型,故必须通过string类对象的成员函数c_str()来实现。
time_h.push_back(atoi(t.substr(0, 2).c_str()));