栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C/C++ 字符串转数字

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C/C++ 字符串转数字

字符串转数字 C

in C
in C++

C有两个转换函数:

  • atoi
  • strtol
    这两个函数都不会出异常 只会执行到出错位置后返回当前结果 默认结果为0
atoi

int atoi (const char * str);

只能转换10进制的数字字符串为数字

#include 

int main(){
  	printf("%d %d %dn",atoi("1000"),atoi("a1000"),atoi("100a0"));
  	return 0;
}

结果

1000 0 100
strtol

long int strtol (const char* str, char** endptr, int base);

参数
str数字字符串
endptr指向数字解析完后的地址(下一位)可为NULL
base进制[2,36]
#include 

int main(){
	char *end;
	const char*s = "0x1000";
	const char*sp="10a3";
	printf("%d ",strtol(s,&end,16));
	printf("[end]:%dn",end-s);
	printf("%d ",strtol(sp,&end,10));
	printf("[end]:%dn",end-sp);
  	return 0;
}

输出

4096 [end]:6
10 [end]:2
cpp stoi

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 参数与strtol的 endptr 参数作用相同 都是指向数字解析完的下一位 可为nullptr

如果base为0 则进制由字符串格式决定

#include 
#include 

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); // 16进制

  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;
}

结果为

2001, A Space Odyssey: 2001 and [, A Space Odyssey]
40c3: 16579
-10010110001: -1201
0x7f: 127
参考
  • atoi
  • strtol
  • stoi
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/847998.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号