string 和 int之間的轉化


int轉換爲string

#include <iostream>
/*
#include <sstream>
using namespace std;


int main()
{
	//第一種:使用itoa
	int aa = 30;
	char c[8];
	itoa(aa, c, 10);//此函數是c語言的函數,只能在windows下使用
	cout<<c<<endl;


	//第二種方法:使用sprintf
	int ab = 31;
	char c1[8];
	int length = sprintf(c1, "%d", ab);
	cout<<c1<<endl;


	//第三種方法:使用stringstream
	int ac = 32;
	stringstream ss;


	ss<<ac;
	string m = ss.str();
	cout<<m<<endl;


	//第四種方法:使用lexical_cast
	int ad = 33;
	//string n = boost::lexical_cast<string>(33);//這裏必須下載boost庫才能使用
	cout<<n<<endl;
}
*/ 
//String轉化爲int

#include <iostream>
#include <sstream>
using namespace std;


//String轉化爲int
int main()
{
	string s = "20";
	char* b;

	const char *k = "25";
	cout<<atoi(k)<<endl;//此函數是c語言的函數,只能在windows下使用

	//方法一 使用strtol
	int i = static_cast<int>(strtol(s.c_str(), &b, 10));
	cout<<i<<endl;

	//方法二 使用sscanf
	int j;
	sscanf("17", "%D", &j);
	cout<<j<<endl;

	//方法三 使用stringstream
	string s1 = "54";
	stringstream ss;
	ss<<s1;

	int n;
	ss>>n;
	cout<<n<<endl;

	//方法四
	//string s2 = "69";
	//int m = boost::lexical_cast<int>(s2);
	//cout<<m<<endl;
	return 0;
}



發佈了50 篇原創文章 · 獲贊 20 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章