C++学习笔记(三):文本文件的写入

愿所有想编程的人能够坚持自己的梦想!不要放弃!微笑

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char mobile[50];
int year;
double a_price;
double d_price;


cout<<"Enter the make of the mobile: ";
cin.getline(mobile,50);
cout<<"Enter the moble year: ";
cin>>year;
cout<<"Enter the original asking price: ";
cin>>a_price;
d_price=0.913*a_price;


//屏幕显示数据
cout<<fixed;
cout.precision(2);
cout.setf(ios_base::showpoint);//设置带小数点,精度为2
cout<<"Make and model: "<<mobile<<endl;
cout<<"Year: "<<year<<endl;
cout<<"Was asking $"<<a_price<<endl;
cout<<"Now asking $"<<d_price<<endl;


//文本输入 
ofstream fout; //创建一个ofstream对象
fout.open("test.txt");   //与test.txt相关联,如无该文件,则创建该文件;
//但注意的是下一次再打开该文件,其文件长度将被截断为0,即原内容全部丢失
fout<<fixed;
fout.precision(2);
fout.setf(ios_base::showpoint);//同上,这里体现出了面向对象的优势
fout<<"Make and model: "<<mobile<<endl;
fout<<"Year: "<<year<<endl;
fout<<"Was asking $"<<a_price<<endl;
fout<<"Now aksing $"<<d_price<<endl;
fout.close(); //与open()方法对应
return 0;
}

结果:

屏幕显示

Enter the make of the mobile: Liu Jing
Enter the moble year: 1986
Enter the original asking price: 13500
Make and model: Liu Jing
Year: 1986
Was asking $13500.00
Now asking $12325.50

与.cpp同一级目录下将被创建一个test.txt文件

打开文件将发现内容也被写入到其中了;

内容如下:

Make and model: Liu Jing
Year: 1986
Was asking $13500.00
Now aksing $12325.50





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值