C++ 字符串和数字的转换

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值