C++中int类型与String类型的相互转换

最近经常用到两种类型的相互转换,从网上找了一些,汇总一下,以备不时之需

int类型转换为String类型
方法一:利用sprintf

#include <iostream>
#include <string>
int main()
{
    int n = 123;
    char t[256];
 
    sprintf(t, "%d", n);
    std::string s(t);
    std::cout << s << std::endl;
 
    return 0;
}

方法二:利用stringstream类(个人最喜欢)

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	int n = 123;
	stringstream ss;
	string str;
	ss << n;
	ss >> str;
	cout << str << endl;
	system("pause");
	return 0;
}

方法三:利用C++11新增的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)

string类型转换为int类型
方法一:利用stringstream类

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
	int n ;
	stringstream ss;
	string str("123");
	ss << str;
	ss >> n;
	cout << n << endl;
	system("pause");
	return 0;
}

方法二:利用标准库atoi、_atoi64…函数

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

猜你喜欢

转载自blog.csdn.net/woniulx2014/article/details/82995006