c++学习笔记——简单文件输入和输出

目的:让程序直接读取为文件,或者让程序输入写到文件中更加方便

c++将读取键盘输入和在屏幕上显示输出(俗称控制台输入\输出)的技巧用于文件输入\输出(文件        I\O)非常简单。

#include<iostream>
int main()
{
    using namespace std;
    char ch ;
    cin >> ch;//输入38.5 5 19.2
    cout << ch <<endl;
    //输入行的第一个字符别赋给ch,第一个字符时3,其字符编码(二进制)被存储在变量ch中。
    //输入和目标变量(char类)都是字符,不需要类型转换.
    //输入队列中的下一个字符为字符8,下一个操作将其对其进行处理。
 return 0;
}
38.5 19.2
3
#include<iostream>
int main()
{
    using namespace std;
    int n;
    cin >> n;//输入38.5 5 19.2
    cout << n <<endl;
    //cin不断读取,直到遇到非数字字符,这里就读取到38,句点将作为输入队列中的下一个字符,
    //将38的二进制编码复制到变量n中
    return 0;
}
38.5 19.2
38
#include<iostream>
int main()
{
    using namespace std;
    double n;
    cin >> n;//输入38.5 5 19.2
    cout << n <<endl;
    //cin不断读取,直到遇到第一个不是浮点数的字符,这里就读取到38.5,
    //将38.5的二进制编码(浮点格式)复制到变量n中
    return 0;
}
38.5 19.2
38.5
#include<iostream>
int main()
{
    using namespace std;
    char words[50];
    cin.getline(words, 50);//输入38.5 5 19.2
    cout << words <<endl;
    //cin不断读取,直到遇到换行符,所有字符都将被存储在数组words中,
    //并在末尾加上一个空字符,换行符将被丢弃。输入队列中下一个字符时下一行字符
    return 0;
}
38.5 19.2
38.5 19.2

写入到文件文本中

文件输入的要求(可类比cout)

(1)必须包含头文件fstream

(2)头文件fstream定义了一个用于处理输出的ofstream类

(3)需要声明一个或者多个ofstream变量(对象),并以对他们就行自行命名,但必须遵循常用的命名规则。

(4)必须指明名称空间std;例如,为引用元素ofstream,必须使用编译指令using或者使用前缀std::

(5)需要将ofstream对象和文件关联起来。为此,方法之一就是使用open()

(6)使用完文件后,应该使用方法close()将其关闭

(7)可结合使用ofstream对象和与运算符<<来输出各种类型的数据。

// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>                  // for file I/O

int main()
{
    using namespace std;

    char automobile[50];
    int year;
    double a_price;
    double d_price;

    ofstream outFile;//这里与cout不同,头文件iostream提供了一个预先定义好的cout的ostream对象
    //但ofstream对象必须自己声明。这里提供了一个声明的实例。
    outFile.open("carinfo.txt");    
    //方法open()接收一个c风格字符串作为参数,它可以是一个字面字符串,也可以是存储在数组中的字符串。
    //使用方法open()将该对象特定文件关联起来
    //这里在程序运行之前,若文件carinfo.txt不存在,方法open()将新建一个名为carinfo.txt的文件,
    //如果文件在程序运行之前存在,默认情况下,将首先截断该文件,
    //也就是将长度截短到零,丢弃原有的内容,然后将新的输出加入到文件夹中。

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

// display information on screen with cout

    cout << fixed;//强制以小数的方式显示
    cout.precision(2);//cout.precision(val)其实就是在输出的时候设定输出值以新的浮点数精度值显示,即小数点后保留val位
    //上述两个控制语句能控制该语句下面的所有输出语句的格式,如若改变格式,再写一个其他格式的语句。
   
    cout.setf(ios_base::showpoint);//以句点形式输出,而不是以e形式输出浮点数;
    cout << "Make and model: " << automobile << endl;
    cout << "Year: " << year << endl;
    cout << "Was asking $" << a_price << endl;
    cout << "Now asking $" << d_price << endl;

// 现在outFile可使用cout的任何方法,

    outFile << fixed;
    outFile.precision(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 $" << d_price << endl;
    
    outFile.close();
    //程序使用完文件后,应该将关闭,这里不需要指定文件名,因为outFile已经同特定的文件夹关联起来了
    //如果忘记关闭文件,程序正常终止时将自动关闭它。
    // cin.get();
    // cin.get();
    return 0;
}
Enter the make and model of automobile: ford
Enter the model year: 2015
Enter the original asking price: 12350
Make and model: ford
Year: 2015
Was asking $12350.00
Now asking $11275.55

读取文本文件

文件输出的要求(可类比cin)

 (1)文件包括头文件fstream

(2)头文件iostream定义了一个用处理输入的ifstream类

(3)需要声明一个或者多个ifstream变量(对象),对其进行自行命名,条件是必须遵守命名规则。

(4)必须使用名称空间std,引用元素ifstream,必须使用编译指令using或前缀std

(5)需要将ifstream对象将文件关联起来。方法之一就是使用open()

(6)使用完文件后,应使用close()方法将其进行关闭

(7)可结合使用ifstream对象和>>运算符来读取各种类型的数据

(8)可结合使用ifstream对象和get()方法读取一个字符,使用ifstream和getline来读取一行字符。

(9)可结合使用ifstream和eof()、fail()等方法来判断输入是否成功

(10)ifstream对象本身被用作测试条件时,如果最后一个读取操作成功,他将本转化成布尔值true,否则被转化成false。

// sumafile.cpp -- functions with an array argument
#include <iostream>
#include <fstream>          // file I/O support
#include <cstdlib>          // support for exit()
const int SIZE = 60;
int main()
{
    using namespace std;
    char filename[SIZE];
    ifstream inFile; 
    //这里区别于cin,文件iostream提供了一个预先定义好的名为cin的istream对象,但ifstream对象必须自行声明
    //这里是一个声明其对象的实例

    cout << "Enter name of data file: ";
    cin.getline(filename, SIZE);
    inFile.open(filename);  // 将ifstream对象inFile和文件关联起来
    //该程序没有使用硬编码文件名 ,而是将用户提供的文件名存储在字符数组filename中,而后将该数组用作open()参数
    
    // 如果试图打开一个不存在的文件用作输入,会导致后面使用ifstream对象进行输入时失败。
    if (!inFile.is_open())//检查文件是否被成功打开的方法时使用is_open(),如果被成功打开,方法is_open()将返回true
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating.\n";
        // cin.get();    // keep window open
        exit(EXIT_FAILURE);
        //函数exit()的原型是在头文件cstdlib中定义的,
        //该头文件中,还定义了一个用于同操作系统通信的参数值EXIT_FAILURE,函数exit终止程序。
    }
    double value;
    double sum = 0.0;
    int count = 0;          // number of items read

    inFile >> value;        // get first value
    while (inFile.good())   // while input good and not at EOF,
    //方法good()在检查可能存在的问题,但是没有is_open()检查的广泛。
    {
        ++count;            // one more item read
        sum += value;       // calculate running total
        inFile >> value;    // get next value
    }

    //检查可能出现的意外
    if (inFile.eof())
    //程序在读取文件时不应超过EOF,如果最后一次读取数据时遇到EOF,方法eof()将返回true
        cout << "End of file reached.\n";
    else if (inFile.fail())
    //如果最后一次读取操作中发生了类型不匹配的情况,方法fail()将返回true(如果遇到EOF,该方法也返回true)
        cout << "Input terminated by data mismatch.\n";
    else
    //最后可能出现的意外就是如果文件受损或者硬件故障,如果最后一次读取文件时发生了这样的问题,方法bad()将返回true。
        cout << "Input terminated for unknown reason.\n";
    
//上面的if语句用于判断循环为何终止。

    if (count == 0)
        cout << "No data processed.\n";
    else
    {
        cout << "Items read: " << count << endl;
        cout << "Sum: " << sum << endl;
        cout << "Average: " << sum / count << endl;
    }
    inFile.close();         // finished with the file
    // cin.get();
    return 0;
}
Enter name of data file: scores.txt
End of file reached.
Items read: 11
Sum: 187
Average: 17

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值