1. itoa
itoa是广泛应用的非标准c语言扩展函数,头文件为 #icnlude<stdlib.h>
char
* itoa(int value,
char
* string,int radix);
#include<iostream> #include<cstdlib> using namespace std; int main(){ int i=15; char str[25]; itoa(i,str,16); cout<<str<<endl; return 0; }
2. sprintf
C的库函数,头文件#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\n",buffer,n);/*“格式输出”*/ return 0; }
3.atoi
C库函数,#icnlude<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\n",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,‘\n‘); for (i=0; str[i] != ‘\0‘; 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; }
字符串与数字之间的转换
时间: 2024-10-24 10:47:08