C++编程思想:文件 字符串 输入输出

标准文件读取和写入

#include <iostream>
#include <fstream>
#include <string>
#include<assert.h>
using std::ifstream;
using std::ofstream;
using std::cout;
using std::endl;
using std::string;

// ******************** 利用getLine 读取和写入文件*************************
int main()
{
	const int sz = 100;
	int i = 1;
	char buf[sz];
	{
		ifstream in("txt.txt",std::ios::in); //read
		ofstream out("txt2.txt",std::ios::out|std::ios::app); //write ,打开模式为可写文件,追加模式,默认为截断模式,就是清空重写

		
	    //*********使用成员函数读取文件内容
		while (in.getline(buf,sz))//当遇到\n的时候停止,也可以默认不写第三个参数,就是\n
		{
			in.get();//吧\n取出来,并丢掉
			//cout << buf << endl;
			//out << buf << endl; //写入到txt2
		}

		in.clear();//清空函数的标志位 没有这个标志位清楚,下面的输入流指针重定位无效

		in.seekg(0, std::ios::beg);//输入流指针重定位
		
		//*************使用全局函数读取文件
		string str;
		while (std::getline(in, str))
		{
			cout << str << endl;
		}

	}
}

字符串输入输出

//********************输入输出字符串流测试*************************

int main()
{
	//输入字符串流
	istringstream s("47 1.414 this is a test"); //如果把47变成4.7 i 就会等于4 f 等于0.7
	int i;
	double f;
	string c;
	s >> i;
	s >> f;

	s >> c;

	cout << i<<endl;
	cout << f << endl;
	cout << c << endl;
	cout << s.rdbuf() << endl;

	//输出字符串流
	cout << "type an int ,a float and a string";
	cin >> i;
	cin >> f;
	cin >> std::ws; //输入一个空格符
	string strBuff;
	std::getline(cin, strBuff);
	ostringstream os;
	os << "interger = " << i << endl;
	os << "float = " << f << endl;
	os << "string = " << strBuff << endl;
	string result = os.str();
	cout << "result : " << result << endl;

}

输入输出流的格式化

//********************* 输入输出流的格式化 ***********************
int main()
{
	ofstream  out("out.txt");
	out.setf(std::ios::unitbuf); //一个标志位,每次out中加入数据,都会刷新流将文件写到 out中,所以即使abort了,文件还是会被写入
	out.setf(std::ios::showpos); //符号标志位,遇到数字显示+号
	out.unsetf(std::ios::showpos); //取消显示+号 
	out << " one " ;
	out << " two " ;
	out << 3 ;
	//abort();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值