<C/C++> IO流 cout/fstream的使用

1. std::count

原文地址:http://www.cnblogs.com/devymex/archive/2010/09/06/1818754.html


cout是C++终端输出函数,类似于C的printf。

下面是我给合原文所写的测试代码:

void TestCout()
{
	cout.setf(ios::showpos | ios::uppercase);			// 显示符号“+-”,十六进制大写输出
	cout << hex << setw(4) << 12 << setw(12) << -12 << endl;	// 十六进制
	cout << dec << setw(4) << 12 << setw(12) << -12 << endl;    // 十进制
	cout << oct << setw(4) << 12 << setw(12) << -12 << endl;	// 八进制
	cout.unsetf(ios::showpos | ios::uppercase);	 // 反转标志
	cout << hex << setw(4) << 12 << setw(12) << -12 << endl;	
	cout << dec << setw(4) << 12 << setw(12) << -12 << endl;
	cout << oct << setw(4) << 12 << setw(12) << -12 << endl;

	cout.setf(ios::fixed); // 浮点精度
	cout << setprecision(0) << 12.05 << endl;
	cout << setprecision(1) << 12.05 << endl;
	cout << setprecision(2) << 12.05 << endl;
	cout << setprecision(3) << 12.05 << endl;
	cout.setf(ios::scientific, ios::floatfield);   // 指数表示
	cout << setprecision(0) << 12.05 << endl;
	cout << setprecision(1) << 12.05 << endl;
	cout << setprecision(2) << 12.05 << endl;
	cout << setprecision(3) << 12.05 << endl;
}

2. fstream

fstream用于文件的流操作。文件输入流ifstream和文件输出流ofstream都是fstream的子类。
void open (const char* filename,
           ios_base::openmode mode = ios_base::in | ios_base::out);

filename: 文件名,有多个重载函数,既可以支持Unicode字符串,也支持Ansi字符串,很方便。
mode: 打开模式,包括以下:


下面为测试代码:
void TestFstream()
{
	//
	// ofstream 文件输出
	char *pBuffer = "This is my test buffer for fstream.\nThe Second line.";
	ofstream ofs;
	ofs.open(TEXT("test.txt"), ios::out); // ios::app 追加
	ofs.write(pBuffer, strlen(pBuffer));
	ofs.close();

	//
	// ifstream 文件输入
	ifstream ifs;
	ifs.open(TEXT("test.txt"), ios::in);
	if (!ifs.is_open())
	{
		return;
	}
	char rdBuffer[17] = {0};
	streampos sp;
	while (!ifs.eof())
	{
		sp = ifs.tellg();		// 获取当前文件指针位置
		cout << "[" << dec << sp << "]";

		ifs.read(rdBuffer, 16);
		cout << rdBuffer;
		memset(rdBuffer, 0, 17);
	}
	cout << flush << endl;
	ifs.close();

	//
	// getline的使用
	ifs.clear();	// 重复利用,调用clear重置流状态
	ifs.open(TEXT("test.txt"), ios::in);
	char line[257] = {0};
	while (!ifs.eof())
	{
		sp = ifs.tellg();
		cout << "[" << dec << sp << "]";

		ifs.getline(line, 256);	// 确保文件每一行不超过buffer的大小
		cout << line;
		memset(line, 0, 256);
	}
	cout << endl;
	ifs.close();
}


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值