C++ 读写文件 ifstream,ofstream,sstream

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HERO_CJN/article/details/86300545

ofstream是从内存到硬盘,ifstream是从硬盘到内存,其实所谓的流缓冲就是内存空间;  
在C++中,有一个stream这个类,所有的I/O都以这个“流”类为基础的,包括我们要认识的文件I/O,stream这个类有两个重要的运算符:  
1、插入器(<<)  
  向流输出数据。比如说系统有一个默认的标准输出流(cout),一般情况下就是指的显示器,所以,cout<<"Write Stdout"<<’\n’;就表示把字符串"Write Stdout"和换行字符(’\n’)输出到标准输出流。  
2、析取器(>>)  
  从流中输入数据。比如说系统有一个默认的标准输入流(cin),一般情况下就是指的键盘,所以,cin>>x;就表示从标准输入流中读取一个指定类型(即变量x的类型)的数据。  
  在C++中,对文件的操作是通过stream的子类fstream(file stream)来实现的,所以,要用这种方式操作文件,就必须加入头文件fstream.h。

string到int的转换

#include <iostream>
int main()
{
    std::stringstream stream;
    int first, second;
    stream<< "456"; //插入字符串
    stream >> first; //转换成int
    std::cout << first << std::endl;
    stream.clear(); //在进行多次转换前,必须清除stream
    stream << true; //插入bool值
    stream >> second; //提取出int
    std::cout << second << std::endl;

重复利用stringstream对象

如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。

构造字符串流的时候,空格会成为字符串参数的内部分界,字符串的空格成为了整型数据与浮点型数据的分解点,利用分界获取的方法我们事实上完成了字符串到整型对象与浮点型对象的拆分转换过程

#include<iostream>
#include<fstream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;

void LoadImages(const string &strFile, vector<string> &vstrImageFilenames, vector<double> &vTimestamps,
                const string& imagefilename, const string& timestampfilename)
{
    ofstream ofimage;
    ofstream ofstamp;
    ifstream f;
    ofimage.open(imagefilename.c_str());
    ofstamp.open(timestampfilename.c_str());
    f.open(strFile.c_str());
    ofimage << fixed;
    ofstamp << fixed;

    // skip first three lines
    string s0;
    getline(f,s0);
    getline(f,s0);
    getline(f,s0);

    while(!f.eof())
    {
        string s;
        getline(f,s);
        if(!s.empty())
        {
            stringstream ss;
            ss << s;
            double t;
            string sRGB;
	    	ss >> t;
            ofstamp << t << endl;
            vTimestamps.push_back(t);
            ss >> sRGB;
	    	ofimage << sRGB << endl;
            vstrImageFilenames.push_back(sRGB);
        }
    }
    ofimage.close();
    ofstamp.close();
}


int main(int argc, char** argv){
	vector<string> imagefilenames;
	vector<double> timestamps;
	string strfile = string(argv[1])+"/rgb.txt";
	string imagefilename = string(argv[1])+"/image.txt";
	string timestampfilename = string(argv[1])+"/timestamp.txt";
	LoadImages(strfile, imagefilenames, timestamps, imagefilename, timestampfilename);
	for(int i = 0; i < timestamps.size(); ++i){
		cout << timestamps[i] << endl;
	}
	return 0;
}

文件格式: 

猜你喜欢

转载自blog.csdn.net/HERO_CJN/article/details/86300545