C++ 的文本操作——写入到文本文件中(不积跬步,无以至千里,之第三步。)

重点语句,均在代码中指出:
ofstream outFile; // outFile 可使用cout可使用的任何方法。
outFile.open(“carinfo.txt”);
cout << fixed;
cout.precision(2);
outFile.setf(ios_base::showpoint);

#include <iostream>
#include <fstream>  // 该头文件定义了一个用于输出的ofstream类
using namespace std;
int main()
{
    char automobile[50];
    int year;
    double a_price;
    double b_price;
    
    // 声明一个或多个ofstream对象,并以自己细化的方式对其进行命名,条件时遵守常用的命名规则。
    ofstream outFile;  // create object for output, outFile 可使用cout可使用的任何方法。
    // 若carinfo.txt 存在,默认丢弃其原有内容,重新接受输入。若不存在,则创建。
    outFile.open("carinfo.txt");  // associate with a file
    cout << "Enter the make and model of automobile:";
    cin.getline(automobile, 50);  // 最多录入49个字符外加1个空字符。
    cout << "Enter the model year:";
    cin >> year;
    cout << "Enter the original asking price:";
    cin >> a_price;
    b_price = 0.913 * a_price;

    //display information on screen with cout 

    // 用一般的方式输出浮点型,例如C++程序在控制台显示的时候大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示
    cout << fixed;  // 加了fixed意味着是固定点方式显示,所以下面的的精度变为了小数的位数
    cout.precision(2);  // 设置精确度为2,并返回上一次的设置
    cout.setf(ios_base::showpoint);  // 显示浮点数小数点后面的零。
    cout << "Make and model: " << automobile << endl;
    cout << "Year: " << year << endl;
    cout << "Was asking $" << a_price << endl;
    cout << "Now asking $" << b_price << endl;

    //now do exact same thing using outFile instead of cout
    outFile << fixed;  // 加了fixed意味着是固定点方式显示,所以下面的的精度变为了小数的位数
    outFile.precision(2);  // 设置精确度为2,并返回上一次的设置 
    outFile.setf(ios_base::showpoint);  // 显示浮点数小数点后面的零。
    outFile << "Make and model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    outFile << "Was asking $" << a_price << endl;
    outFile << "Now asking $" << b_price << endl;
    outFile.close(); // done with file 
    return 0;
}

输出结果:

在这里插入图片描述
文件内容:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值