atoi(),itoa(),atol(),atof ()
atoi(將字元串轉換成整型數):atoi(const char *nptrnt )
函數說明 : atoi()會掃描參數nptr字元串,跳過前面的空格字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字元串結束時(" ")才結束轉換,並將結果返回。
itoa(將整型數轉換成字元串):char *itoa( int value, char *string,int radix);
原型說明:
value:欲轉換的數據。
string:目標字元串的地址。
radix:轉換後的進位數,可以是10進位、16進位
#include<iostream>
using namespace std;
int atoi1(char *s)
{
int sign=1,num=0;
if(*s=="-")
sign=-1;
s++;
while((*s)!=" ")
{
num=num*10+(*s-"0");
s++;
}
return num*sign;
}
char *itoa(int val, char *buf, unsigned radix)
{
char *p;
char *firstdig;
char temp;
unsigned digval;
p = buf;
if(val <0)
{
*p++ = "-";
val = (unsigned long)(-(long)val);
}
firstdig = p;
do{
digval = (unsigned)(val % radix);
val /= radix;
if (digval > 9)
*p++ = (char)(digval - 10 + "a");
else
*p++ = (char)(digval + "0");
}while(val > 0);
*p-- = " ";
do{
temp = *p;
*p = *firstdig;
*firstdig = temp;
--p;
++firstdig;
}while(firstdig < p);
return buf;
}
int main()
{
char *s="-16734",buf[20];
int a=34567;
cout<<atoi1(s)<<endl;
cout<<itoa(a,buf,10)<<endl;
return 0;
}
atof(將字元串轉換成浮點型數);double atof(const char *nptr);
函數說明 :
atof()會掃描參數nptr字元串,跳過前面的空格字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字元串結束時(" ")才結束轉換,並將結果返回。參數nptr字元串可包含正負號、小數點或E(e)來表示指數部分,如123.456或123e-2。
#include<iostream>
using namespace std;
double myatof(const char* sptr)
{
double temp=10;
bool ispnum=true;
double ans=0;
if(*sptr=="-")//判斷是否是負數
{
ispnum=false;
}
sptr++;
while(*sptr!=" ")//尋找小數點之前的數
{
if(*sptr==".")
{
sptr++;
break;
}
ans=ans*10+(*sptr-"0");
sptr++;
}
while(*sptr!=" ")//尋找小數點之後的數
{
ans=ans+(*sptr-"0")/temp;
temp*=10;
sptr++;
}
if(ispnum)
return ans;
else
return ans*(-1);
}
int main()
{
char *s="-167.678";
cout<<myatof(s)<<endl;
return 0;
}
atol(將字元串轉換成長整型數):long atol(const char *nptr);
函數說明 : atol()會掃描參數nptr字元串,跳過前面的空格字元,直到遇上數字或正負符號才開始做轉換,而再遇到非數字或字元串結束時(" ")才結束轉換,並將結果返回。
#include<iostream>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
#define N 50
long my_atol(const char *nptr)
{
int c;
long total = 0;
int sign;
while(isspace((int)(unsigned char)*nptr))//跳過前面的空格
++nptr;
c = (int)(unsigned char)*nptr++;
sign = c;
if(c == "-" || c == "+")
c = (int)(unsigned char) *nptr++;
while(isdigit(c))
{
total = 10 * total + c- "0";
c = (int)(unsigned char)*nptr++;
}
if(sign == "-")
return -total;
else
return total;
}
int main(void)
{
char str[N];
cout<<"Enter a string:"<<endl;;
fgets(str,N,stdin);
cout<<my_atol(str)<<endl;
return 0;
}
更多IT精品課程,訪問中公優就業官網:http://xue.ujiuye.com
勤工儉學計劃」,給你一個真正0元學習IT技術的機會!
http://www.ujiuye.com/zt/qgjx/?wt.bd=mmxtt
找工作太難?不是你不行,我們來幫你!
http://www.ujiuye.com/zt/jyfc/?wt.bd=mmxtt
![](https://pic.pimg.tw/zzuyanan/1488615166-1259157397.png)
![](https://pic.pimg.tw/zzuyanan/1482887990-2595557020.jpg)
※mybatis 詳解——動態SQL
※是的,我就是不想眼睜睜地,過著日復一日的生活
※mybatis詳解——properties以及別名定義
※常見排序演算法
TAG:IT優就業 |
※Laboratoire gallia 法國奶粉銷售冠軍
※巴黎高科學院訪問教授Laurent CATOIRE應邀在機動學院作學術報告
※艾滋病藥物DovatoIII期數據公布 雙葯療法效果達到預期