1. itoa,非标准的C语言扩展函数,头文件为 #include<stdlib.h>
char* itoa (int value, char* string, int radix);
#include<algorithm> #include<cstdlib> #include<cstring> using namespace std; int main(){ char str[10]; int n=12345; itoa(n,str,10); cout<<str[2]<<endl; string newStr(str); cout<<newStr[3]<<endl; return 0; }
2. springf,格式化数据到字符串缓冲区,头文件为 #include<stdlib.h>
int sprintf( char *buffer, const char *format, [ argument] … );
#include<stdio.h> #include<stdlib.h> int main() { char buffer[50]; int n,a=5,b=3; n = sprintf(buffer,"%dplus%dis%d",a,b,a+b); printf("[ %s ] is a string %d chars long ",buffer,n);/*“格式输出”*/ return 0; }
3. atoi,C库函数, 将字符串变为数字,头文件为 #include<stdlib.h>
int atoi(const char *nptr);
#include<stdlib.h> #include<stdio.h> int main(void) { double n; char*str="12345.67"; n=atoi(str); printf("string=%s integer=%d ",str,(int)n); return 0; }
4. 写一个atoi的实现函数
#include <iostream> using namespace std; void main(void){ char str[20]; int i,n=0; cout<<"Enter the string:"; cin.getline(str,20,' '); for (i=0; str[i] != ' '; i++) n = n*10+(str[i]-'0'); cout<<"Corresponding number is "<<n<<endl; cout<<"The digits of the number from low to high is "; while(n){ cout<<n%10<<','; n/=10; } cout<<endl; }