- int->string:to_string()函数
- string->int:stoi()函数
#include<iostream>
using namespace std;
#include<string>
#include<typeinfo>
void test() {
//1. string -> int
string s = "123";
int str2i = stoi(s);
cout << typeid(str2i).name() << endl;
//2. int -> string
int i = 456;
string i2str = to_string(i);
cout << typeid(i2str).name() << endl;
}
int main() {
test();
system("pause");
return 0;
}
方法二
#include <sstream>
void i2s(int num, string& str){
stringstream ss;
ss << num;
ss >> str;
}
void s2i(string str, int& num){
stringstream ss;
ss << str;
ss >> num;
}