C++中stringstream实现C中sprintf与atoi功能
来源:互联网 发布:js的this指向 编辑:程序博客网 时间:2024/05/29 19:00
目前对C语言的使用比较多,C++ 的经验不是很多。
用stringstream 实现 C 中的sprintf 以及atoi函数的方法。
#include <iostream>#include <string>#include <sstream>#include <stdio.h>#include <stdlib.h>using namespace std;int main(){int i=24;string name("liukang");//C++ stringstream int->str;stringstream sstr;sstr<<"my name :"<<name<<","<<i<<";"<<hex<<i;string str=sstr.str();cout<<str<<endl;//C sprintf()char buf[100]={0};sprintf(buf, "my name :%s,%d;%x",name.c_str(),i,i);cout<<buf<<endl;//C++ stringstream str->int;int num=0;string p("30");stringstream ss;ss<<p;ss>>num;cout<<"num="<<num<<endl;//C atoi()int n=0;cout<<"num="<<atoi(p.c_str())<<endl;return 0;}
两个常用API:
#include <iostream> #include <algorithm> #include <string> #include <numeric> #include <vector> #include <cstdio> #include <sstream> using namespace std; //c++方法:将数值转换为string string convert_to_string(double x) { ostringstream o; if(o << x) return o.str(); return "conversion error"; } //c++方法,将string转化为数值 double convert_from_string(const string &s) { istringstream i(s); double x; if(i >> x) return x; return 0.0; } int main(int argc,char *argv[]) { //将数值转换为string的第一种方法:c方法 char b[10]; string a; sprintf(b,"%d",1975); //数值转化为string a=b; cout<<a<<endl; string cc=convert_to_string(1976); cout<<cc<<endl; string dd="115165"; int p=convert_from_string(dd)+2; cout<<p<<endl; return 0; }
0 0
- C++中stringstream实现C中sprintf与atoi功能
- c中printf实现atoi实现
- 模拟C库中atoi与itoa
- C/C++中sscanf && sprintf()
- c语言中atoi函数
- 利用strstr与atoi的结合实现一个C语言获取文件中数据的工具
- 深入分析C中不安全的sprintf与strcpy
- C语言中sprintf用法详解
- C语言中sprintf用法详解
- C语言中sprintf()函数的用法
- C语言中sprintf()函数的用法
- C\C++中sprintf的用法
- C中不安全的 sprintf 和 strcpy
- C语言中sprintf()函数的用法
- C/C++中sprintf的用法
- C语言中sprintf()函数的用法
- C 语言中sprintf的用法
- C语言中sprintf()函数的用法
- 私人定制--家庭理财软件
- 第一天写博客,希望能够整理出学习的思路
- iPhone,iPad如何获取WIFI名称即SSID
- 深刻理解Java编程的7个例子
- java调用本地程序,两个命令systeminfo,notepad
- C++中stringstream实现C中sprintf与atoi功能
- OK6410 SD卡一键烧写之我见
- 手把手实现企业级开源监控软件cacti+nagios+ntop整合(图解)
- RMAN那些事
- 开始→运行(cmd)命令大全
- hdu 1251 统计难题
- pjsip2.1.0 vidgui客户端注册到asterisk
- Java异常处理综合例子(try、catch、finally、throws、throw) .
- arp