C++字符串转换

stoi  str的文本转化为为int整数。
这可以让str直接转成ascii码?!
int stoi (const string& str, size_t* idx = 0, int base = 10);
int stoi (const wstring& str, size_t* idx = 0, int base = 10);
idx如果不为空,则会返回一个字符串中遇到的第一个字符(非数字)的字符下标,最后一个base是默认10进制。
    string str_dec = "2001, A Space Odyssey";
    string str_hex = "4";
    string str_bin = "-1";
    string str_auto = "0x7f";

    string::size_type sz;   // 在不同的机器上,长度是可以不同的,并非固定的长度,会自己适配机器
    int i_dec =  stoi (str_dec,&sz);//代表取出一个不带空格的字符串
    int i_hex =  stoi (str_hex,nullptr,16);//nullptr,C++11中的空指针,都一样
    int i_bin =  stoi (str_bin,0,2);
    int i_auto =  stoi (str_auto,NULL,0);//0代表默认10进制

   //cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
    cout << sizeof(sz)<<"|"<<str_dec.substr(sz) <<endl;//sizeof=8,占4个字符长度
    cout << str_hex << ": " << i_hex << '\n';
    cout << str_bin << ": " << i_bin << '\n';
    cout << str_auto << ": " << i_auto << '\n';

stol long int型
stoul
stoll
stoull
stof  浮点型
   string orbits ("1.1 2.2     3.3");
   string::size_type sz;     // alias of size_t

  float a =  stof (orbits,&sz);//sz相当于一个字符串长度
  orbits.erase(0,sz); cout<<orbits<<endl;
  float b =  stof (orbits,&sz);
  float c =  stof (orbits.substr(sz));
  cout<<a<<" "<<b<<" "<<c<<endl;
通过这种方式,可以让一连串字符串转变成数据
stod  双精度
   string orbits ("1.1 -2.233     3.3");
   string::size_type sz;     // alias of size_t

  double a =  stod (orbits,&sz);//sz相当于一个字符串长度
  orbits.erase(0,sz); cout<<orbits<<endl;
  double b =  stod (orbits,&sz);
  double c =  stod (orbits.substr(sz));
  cout<<a<<" "<<b<<" "<<c<<endl;
atoi()  解析字符串返回int。
   char s[]="123";
   int i=atoi(s);

总结:
stoi用来转哈string的,atoi转化的是char[].
char[]转string可以直接赋值或者用一个循环
string转char
str.data()
str.c_str()
str.copy()
个人感觉stoi的能力还是要比atoi的能力要大一些的,stoi可能往往要比atoi要好用。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值