c++对文件操作的支持(一)

#include <stdio.h>

#include <iostream>

#include <fstream>

using namespace std;

void main()

{       int a,b;

char c;

ofstream fout("test.txt");

fout<<" "<<0<<" "<<1<<" "<<4<<endl;

fout<<" "<<3<<" "<<4<<" "<<'d'<<endl;

ifstream fin("test.txt");

while (!fin.eof())

{

    fin>>a>>b>>c;

    cout<<a<<" "<<b<<" "<<c<<endl;

}

cin>>a;

}
#include <iostream> 

#include <fstream> 

#include <string> 

#include <assert.h>

#include <sstream>

using namespace std;

/**

 * double转换为string

 */

string doubleToString(double d) {

 ostringstream os;

 if (os << d)

  return os.str();

 return "invalid conversion";

}

/**

 * string转double

 */

double stringToDouble(string str) {

 istringstream iss(str);

 double x;

 if (iss >> x)

  return x;

 return 0.0;

}



int main() 

{ 

    ofstream o_file;

    ifstream i_file;

    string out_text; 

    o_file.open("xie.txt"); 

    i_file.open("xie1.txt"); 

    assert(i_file.is_open()&&o_file.is_open()) ;

    while(!i_file.eof())  //while(i_file>>out_text)   也可判断结束

    {

        //将其输出到字符串中的作用是为了解决将0.000001类型输出时为科学计数法的问题

        i_file>>out_text;     //必须使用空格隔开

        static int i = 0;            //其作用为在文件结尾不会出现空的一行

        if(i ==0) o_file<<out_text;

        else    o_file<<endl<< out_text;

        i = 1;

        cout<<stringToDouble(out_text)<<endl;

        cout<<doubleToString(stringToDouble(out_text))<<endl;

    }

    i_file.close();

    o_file.close(); 

    return 0; 

}
//xie1.txt

0.000001

0.000012

0.01

0.000001

你可能感兴趣的:(文件操作)