昨天写leetcode oj时要用到string类型转成int型,于是百度了一番,现归纳总结如下。(ps:归纳不全面,大家可补全。。。)
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
class Solution {
public:
string intTOstring1(int num); //int型转换为string型,采用ostringstream
string intTOstring2(int num); //int型转换为string型,采用stringstream
string intTOstring3(int num); //int型转换为string型,采用sprintf
string intTOstring4(int num); //int型转换为string型,采用itoa
int stringTOint1(string s); //string型转换为int型,采用stringstream
int stringTOint2(string s); //string型转换为int型,采用string.c_str()和atoi
};
string Solution::intTOstring1(int num)
{
ostringstream os;
os << num;
string s;
s = os.str(); //将int型转换为string型
return s;
}
string Solution::intTOstring2(int num)
{
stringstream ss;
ss << num;
string s;
ss >> s;
return s;
}
string Solution::intTOstring3(int num)
{
char *ch = new char[20];
sprintf(ch, "%d", num);
string s = ch;
delete ch;
ch = NULL;
return s;
}
string Solution::intTOstring4(int num)
{
char *ch = new char[20];
itoa(num, ch, 10);
string s;
s = ch;
delete ch;
ch = NULL;
return s;
}
int Solution::stringTOint1(string s)
{
stringstream ss;
ss << s;
int num;
ss >> num;
return num;
}
int Solution::stringTOint2(string s)
{
return atoi(s.c_str());
}
void main()
{
Solution so;
cout << "*************** int -> string *******************" << endl;
cout << "采用ostringstream将int型转换为string型:" << so.intTOstring1(123) << endl;
cout << "采用stringstream将int型转换为string型:" << so.intTOstring2(101) << endl;
cout << "采用sprintf将int型转换为string型:" << so.intTOstring3(234) << endl;
cout << "采用itoa将int型转换为string型:" << so.intTOstring3(876) << endl;
cout << "\n" << "*************** string -> int *****************" << endl;
cout << "采用stringstream将string型转换为int型:" << so.stringTOint1("65") << endl;
cout << "采用string.c_str()和atoi()将string型转换为int型:" << so.stringTOint1("73") << endl;
}
结果:
补充:
1) c++中有3个输入输出控制类,分别为:istringstream。ostringstream、stringstream类。代码中用到了后2类。其中:
istringstream类执行C++风格的串流的输入操作。
ostringstream类执行C风格的串流的输出操作。
stringstream类同时支持C风格的串流的输入输出操作。
要使用这3类,必须包含头文件#include<sstream>
2) 当要清空ostringstream中数据时clear()函数不起作用,而应该采用ostringstream.str(“”)。证明如下:
void main()
{
int num1 = 1, num2 = 2;
ostringstream os;
string s1, s2;
cout << "采用os.clear()清空流中数据,结果如下:" << endl;
os << num1;
s1 = os.str();
cout << "s1 = "<< s1 << endl;
os.clear();
os << num2;
s2 = os.str();
cout << "s2 = " << s2 << endl;
}
void main()
{
int num1 = 1, num2 = 2;
ostringstream os;
string s1, s2;
cout << "采用os.str("")清空流中数据,结果如下:" << endl;
os << num1;
s1 = os.str();
cout << "s1 = "<< s1 << endl;
os.str("");
os << num2;
s2 = os.str();
cout << "s2 = " << s2 << endl;
}
原因是: ostringstream.clear()