C++的stringstream类(来源:<sstream>)
1.字符串到数字
1 2 3 4
| string str = "854"; stringstream sstr(str); int x; sstr >> x;
|
2.数字到字符串
1 2 3 4 5
| stringstream sstr; string str; double x = 154.83; sstr << x; str = sstr.str();
|
- 缺点:处理大量数据转换速度较慢。stringstream不会主动释放内存,如果要在程序中用同一个流,需要适时地清除一下缓存(用stream.str(“”)和stream.clear()).
- 注:
>>
是流提取符,<<
是流插入符
C标准库sprintf、sscanf函数(来源:<stdio.h> or <cstdio>)
1.用sprintf函数将数字转换成字符串(char[])
1 2 3
| int val = 1234; char str[10]; sprintf(str,"%d",val);
|
2.用sscanf函数将字符串(char[])转换成数字
1 2 3 4 5
| char str[] = "15.455"; int i; float fp; sscanf( str, "%d", &i ); sscanf( str, "%f", &fp );
|
C标准库atoi等与itoa等函数(来源:<stdlib.h> or <cstdlib>)
1.用atoi函数将字符串(char)转换成数字*
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| string a = "1234"; const char *b = "1234"; char c[5]="1234";
int d = atoi(a.c_str()); int e = atoi(b); int f = atoi(c);
char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff"; char * pEnd; long int li1, li2, li3, li4; li1 = strtol (szNumbers,&pEnd,10); li2 = strtol (pEnd,&pEnd,16); li3 = strtol (pEnd,&pEnd,2); li4 = strtol (pEnd,NULL,0);
|
2.用itoa函数将数字转换成字符串(char)*
- 注:itoa函数非标准函数
- 一个更标准的用法是采用sprintf(如上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int num = 125; char str[10]; itoa(num, str, 16);
|
C++的to_string与stoi等函数(来源:<string>)
1.用to_string函数将数字转换为字符串(string)
1
| string to_string(T value);
|
2.用stoi等函数将字符串(string)转换为数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
string str = "115.5xy"; int val = std::stoi(str,0,2); long val1 = std::stol(str); float val2 = std::stof(str);
|