一、int转换成string
Ⅰ、to_string函数
c++11标准增加了全局函数std::to_string:
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
Example:
// to_string example
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
Output
pi is 3.141593
28 is a perfect number
Ⅱ、借助字符串流
标准库定义了三种类型字符串流:istringstream,ostringstream,stringstream,看名字就知道这几种类型和iostream中的几个非常类似,分别可以读、写以及读和写string类型,它们也确实是从iostream类型派生而来的。要使用它们需要包含sstream头文件。
除了从iostream继承来的操作
1.sstream类型定义了一个有string形参的构造函数,即: stringstream stream(s); 创建了存储s副本的stringstream对象,s为string类型对象
2.定义了名为str的成员,用来读取或设置stringstream对象所操纵的string值:stream.str(); 返回stream中存储的string类型对象stream.str(s); 将string类型的s复制给stream,返回void
Example:
int aa = 30;
stringstream ss;
ss<<aa;
string s1 = ss.str();
cout<<s1<<endl; // 30
二、string转换成int
Ⅰ、采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等
Example:
std::string str = "123";
int n = atoi(str.c_str());
cout<<n; //123
Ⅱ、采用sstream头文件中定义的字符串流对象来实现转换
istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
int i;
is >> i; //从is流中读入一个int整数存入i中
参考资料:
https://www.cnblogs.com/smile233/p/8379802.html
http://blog.csdn.net/loving_forever_/article/details/51285703
http://blog.csdn.net/lxj434368832/article/details/78874108
https://www.cnblogs.com/aminxu/p/4704281.html