【C++基礎編程】#022 字符串string和整型int相互轉換基本方法

1. int 轉化爲 string

利用to_string()函數即可。
格式string str = to_string(number);

需引入頭文件:

#include<string>

舉例說明:

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

int main() {	
	
	int number = 1001;
	string str = to_string(number);
	cout << str << endl;			//輸出:1001

	system("pause");
	return 0;
}

2. string 轉換爲 int

利用stoi()函數即可。(stoi == string to int(個人理解))
格式int number = stoi(str.c_str());

需引入頭文件:

#include<string>

舉例說明:

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

int main() {	
	
	string str = "1001";
	int number = stoi(str.c_str());
	cout << number << endl;			//輸出:1001

	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章