如果你是在C++11之前,可能比较麻烦
string->int (#include <cstdlib>)
string
s(
"123");
int a =
atoi(s.
c_str());
cout << a;
int->string
1.使用stringstream (#include <sstream>)
stringstream ss;
ss <<
12;
string s;
ss >> s;
cout << s;
2.使用sprintf
char c_str[
100];
sprintf(c_str,
"%d",
12);
string
s(c_str);
cout << s;
而C++11中提供了更简单的方案:
string->int
string s =
"123";
int a =
std::stoi(s);
cout << a;
函数原型在这
int stoi (const string& str, size_t* idx = 0, int base = 10);
就是要注意的是,这里的idx是个指针,而非下标,指向开始转换的地方
当然,你也可以很自然的想到,还有
-
stol
- Convert string to long int (function template )
-
stoul
- Convert string to unsigned integer (function template )
-
strtol
- Convert string to long integer (function )
-
stof
- Convert string to float (function template )
-
stod
- Convert string to double (function template )
int->string
int a =
123;
string s =
std::to_string(a);
cout << s;
转成string SO EASY~