1) 数值转字符串
C++11提供了若干to_string(T value)
函数将T类型的数值转换为字符串形式
string to_string(int value)
string to_string(long value)
string to_string(double value)
代码示例
int a = -100;
long b = 19999;
double c = -78.986;
cout << "a: " << to_string(a) << endl;
cout << "b: " << to_string(b) << endl;
cout << "c: " << to_string(c) << endl;
输出如下,
a: -100
b: 19999
c: -78.986000
2) 把数字型字符串转数值
函数:stoi, stod, stol, stold, stoll, stoul, stoull
函数原型:
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
Example:
// stoi example
#include <iostream> // std::cout
#include <string> // std::string, std::stoi
int main ()
{
std::string str_dec = "2001, A Space Odyssey";
std::string str_hex = "40c3";
std::string str_bin = "-10010110001";
std::string str_auto = "0x7f";
std::string::size_type sz; // alias of size_t
int i_dec = std::stoi (str_dec,&sz);
int i_hex = std::stoi (str_hex,nullptr,16);
int i_bin = std::stoi (str_bin,nullptr,2);
int i_auto = std::stoi (str_auto,nullptr,0);
std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
std::cout << str_hex << ": " << i_hex << '\n';
std::cout << str_bin << ": " << i_bin << '\n';
std::cout << str_auto << ": " << i_auto << '\n';
return 0;
}
参考链接
https://www.cnblogs.com/zpcoding/p/10654750.html
http://www.cplusplus.com/reference/string/stoi/
3) 字符 与 数字 的转换
char a = 'a';
int num = 1;
cout << a + num << endl;
// 输出 98
// 如果想输出得到'b'呢??
cout << char(a + num) << endl;
// 输出 b
char b = 'e';
cout << b - a << endl;
// 输出 4