stringstream、fprintf

stringstream是c++的一个字符串操作的class


fprintf是c的一个打开文件后,往文件中写入字符的函数(同样的还有printf,sprintf)


#include "stdafx.h"
#include "iostream"
#include "string"
#include "sstream"
using namespace std;
#include "iomanip"
 
 
// 填充字符长度,可以用来做数据切分或者类型转化
string i2s(int i, int fill_len = 0, char fill_char = '0')
{
	stringstream ss;
	ss << setw(fill_len) << setfill(fill_char) << i;
	return ss.str();
}
 
 
int _tmain(int argc, _TCHAR* argv[])
{
//===============================================================================================
// stringstream的使用
	// 1、可以利用i2s来产生或者遍历一些文件
	cout << i2s(7, 4, 'c') << endl;
 
 
	// 2、可以利用stringstream在合适的地方代替sprintf
	double f = 0.014;
	char str[10];
	stringstream ss;
//	sprintf(str, "%d", f);	// 因为是double,但是使用了"%d"导致一个错误
	ss << f;
	ss >> str;				// 自动推导要转换的类型,这里可以用template把stringstream封装成一个转换函数
	cout << str << endl;
	// 用完清空一下stringstream
	ss.str("");				// 不用clear,是因为clear是ios类继承过来,用于清错误标志的
 
 
	// 3、切分带有空格的字符串
	string s = "my name is zeng raoli";
	string tmp;
	stringstream ss2;
	ss2 << s;
	while (1)
	{
		tmp = "";
		ss2 >> tmp;
		if (tmp.length() == 0)
		{
			break;
		}
		cout << tmp << endl;
	}
	ss2.str("");	
//===============================================================================================
// stringstream的使用
 
 
 
//===============================================================================================
// fprintf的使用:对于c的打开文件太久没用了 试试再用用。。
	FILE *out_put_file = NULL;
	out_put_file = fopen("1.txt", "w");
	if (out_put_file)
	{
		fprintf(out_put_file, "%s\r\n", "my name is zeng raoli");
	}
	fclose(out_put_file);
 
 
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值