C++ 数字和字符串转换函数的总结

char[] 转 数字

#incldue <cstdlib>
 	
double atof (const char* str);

int atoi (const char * str);

long int atol ( const char * str );

long long int atoll ( const char * str );

float strtof (const char* str, char** endptr); 
/*
	endptr 用来存储该字符串空格的子串,也可以为 NULL, 如:
		char a[] = "1234.5678 1.2";
		char *b;
		float c = strtof(a, &b);
		printf("%f\n%s\n",c,b);
	
	输出结果:
		1234.567749
 		1.2
*/

long double strtold (const char* str, char** endptr);

long long int strtoll (const char* str, char** endptr, int base);
/*
	base 为转译后的进制, base = 0时,默认为10进制, 如:
		char a[] = "111";
		long c = strtol(a, NULL, 2);
  			printf("%ld\n",c);
  		
  		输出结果:
 			7
*/

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

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

数字 转 char[]

#include <cstdio>

/*
	sprintf, 不但可以将数字转为char[], 还支持格式化转译
*/
int sprintf ( char * str, const char * format, ... );

char[10] s;
sprintf(s, "%d", 123); //产生"123"
sprintf(s, "%5d%5d", 123, 4567); //产生:"  123 4567"

string 和 char[] 互换

#include <string>
#include <cstring> // strcpy()

string -> char[]
	string str ("Please split this sentence into tokens");
	char cstr[str.length()];
	strcpy (cstr, str.c_str());

char[] -> string
	string a = cstr;
	string b(cstr);

string 转 数字

#include <string>

/*
	idx 用来存 字符串 转为 数字 后剩下的子串
	base 进制
*/

int stoi (const string&  str, size_t* idx = 0, int base = 10);

long stol (const string&  str, size_t* idx = 0, int base = 10);

unsigned long stoul (const string&  str, size_t* idx = 0, int base = 10);

long long stoll (const string&  str, size_t* idx = 0, int base = 10);

unsigned long long stoull (const string&  str, size_t* idx = 0, int base = 10);

float stof (const string&  str, size_t* idx = 0);

double stod (const string&  str, size_t* idx = 0);

long double stold (const string&  str, size_t* idx = 0);

数字 转 string

#include <string>

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值