stringstream替换sprintf

一、为什么要替换?

答:C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更安全的操作。

int n = 9999;
char sz[10];
sprintf(sz, "abcdefghijklmn%f", n);
	

存在的问题:

1、没有检查缓冲区是否溢出,大小是否足够;

2、没有检查格式化符是否匹配;


修改后的代码:

int n = 9999;
char sz[10];
	
stringstream ssTmp;
ssTmp << n;
ssTmp >> sz;
	

二、实际应用

1、int 转 string

#include <string>
#include <sstream>

#include <stdlib.h>

using namespace std;

int main(int argc, char **argv)
{
	int n = 9999;
	string str;

	stringstream ss;
	ss << n;
	ss >> str;

	cout << str << endl;
	
	system("pause");
	return 0;
}
2、int 转 char*

#include "stdafx.h"

#include <iostream>
#include <string>
#include <sstream>

#include <stdlib.h>

using namespace std;

int main(int argc, char **argv)
{
	int n = 9999;
	char sz[16] = "";

	stringstream ss;
	ss << n;
	ss >> sz;

	cout << sz << endl;
	
	system("pause");
	return 0;
}

3、同一个stringstream进行多次转换之前,必须进行clear操作

#include "stdafx.h"

#include <iostream>
#include <string>
#include <sstream>

#include <stdlib.h>

using namespace std;

int main(int argc, char **argv)
{
	int n1 = 9999;
	int n2 = 99;
	string strN1, strN2;

	stringstream ss;
	ss << n1;
	ss >> strN1;

	ss.clear();

	ss << n2;
	ss >> strN2;

	cout << strN1 << endl;
	cout << strN2 << endl;
	
	system("pause");
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值