C++中的类型转换种类繁多,很容易出错。本文主要总结,在何种情形该使用什么类型转化。
1. char* >> int
- atoi
char s[100];
int i=atoi(s); - sscanf
int sscanf(const char *str, const char *format, …);
sscanf(s,”%d”,&i);
*stringstream
as follows
2. int >> char * : sprintf
int n=10000;
chars[10];
sprintf(s,”%d”,n);// s中的内容为“10000”
这样就利用sprintf将int转化成字符串或者char,但是这种转化方式也存在隐患,我们将在下文提到。
3. 万能转化:stringstream
- This class is inluded in
先来看一下sprintf可能存在的隐患:
int n=10000;
char s[10];
sprintf(s,”%f”,n);// 看!错误的格式化符
那么在C++中,如何更好地将int转化成string呢?
string result=”10000”;
int n=0;
stream<
4. Why not itoa?
C语言中,字符串的处理始终是一个硬伤。标准库之所以提供atoi,是因为返回的是一个标准类型;而atoi,返回的是一个字符串。那么如何返回字符串呢?
1)全局固定内存:线程安全无法保证。
2)每次调用进行malloc空间:容易内存泄露。
3)传入指针:实质和sprintf一样
int sprintf(char * restrict str, const char * restrict format, …);