c++数字与字符串转换方法小结

整型转字符串

1. sstream转换

头文件

#include<sstream>

范例

int i=0;
string out;
stringstream ss;
ss<<i;
ss>>out;
cout<<out;
//输出字符串0

2.to_string()

头文件

#include<string>

范例

int i=0;
string str;
str=to_string(i);
cout<<str;
//输出字符串0

注:不做相关设置,to_string()在devcpp中是无法使用的,如要强行使用,网上有很多讲的很好的文章

3.stoi()

头文件

#include <string>

范例

//原型:stoi(字符串,起始位置,n进制)
stoi(str, 0, 2); //将字符串 str 从 0 位置开始到末尾的 2 进制转换为十进制

注:不建议使用

字符串转整型

1.atoi()

头文件

#include<cstdlib>

范例

string s = "123"; 
int a = atoi(s.c_str());

2.sstream

头文件

#include<sstream>

范例

int i;
string out="123";
stringstream ss;
ss<<out;
ss>>i;
cout<<i;
//输出整数123

浮点类型转字符串

1.to_string()(省略,同整型转字符串)

2.sstream

头文件

#include<sstream>

范例

double fNumber = 3.1415926535;
stringstream ss;
ss << fNumber << flush;
string sNumber = ss.str();

3.sprintf_s()

头文件

#include<cstdio>

范例

char ch[20];
double d=3.14;
sprintf_s(ch,"%f",d);
string str=ch;
//这样就得到了str=3.14字符串

字符串转浮点类型

1.atof()

头文件

#include<cstdlib>

范例

double d;
string str = "3.14";
d = atof(str.c_str());
发布了45 篇原创文章 · 获赞 0 · 访问量 989

猜你喜欢

转载自blog.csdn.net/qq_41985293/article/details/104161085