【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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章