1 流和基本文件I/O
流(stream)是由字符构成的“流”(flow)
流向程序为输入流,流出为输出流
一般使用文件来I/O,因为程序结束之后,文件仍然会被保留,便于储存
文件I/O
文件I/O需要包含有fstream预编译指令,用到输入文件流的变量类型ifStream和输出文件流的outStream
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
//定义两个类型的变量
ifstream ins;
ofstream out;
int main()
{
//用open函数打开文件,注意,输入流需要此文件存在
ins.open("1.txt");
//输出流不要求,没有会自动创建一个
out.open("2.txt");
out<<"321018"<<endl;
ins.close();
out.close();
}
但是这种输入会把文件里面的数据先清除再输出
所以改成out.open(“2.txt”:ios::app);这时候就能在文件末尾添加数据
读取文件里的数据
int n;
//读取文件中的int格式数据
while(ins>>n){
p[c1]=n;
c1++;
}
字符I/O
get和put函数
get得到的是单个的字符,put输出的也是单个字符
char c1;
cin.get(c1);
cout.put(c1)
这是基本用法
但是空格和换行也是会被get函数接收,所以为了不接收这些无意义字符
我们可以用到putback函数,该函数可以将参数放回到输入流
简单的运用小项目,读取文件里最大和最小的数
#include "stdafx.h"
#include <fstream>
#include <iostream>
using namespace std;
ifstream ins;
ofstream out;
int main()
{
ins.open("1.txt");
int c1 = 0;
double *p = new double[];
double n;
while(ins>>n){
p[c1]=n;
c1++;
}
ins.close();
double max=p[0];
double min=p[0];
//cout<<c1<<endl;
for (int i=0;i<c1-1;i++)
{
if (max<p[i+1])
{
max = p[i+1];
}
if (min>p[i+1])
{
min = p[i+1];
}
}
cout<<max<<endl;
cout<<min<<endl;
}