字符串與數字的相互轉換

在寫程序的時候常常碰到字符串與數字相互轉換的問題,這裏做一個小小的總結。

    字符串與數字的轉換的方法比較多,按照不同的開發環境可以分爲C/C++/MFC,當然這三者存在着包含關係,在C開發環境中實現的方法在C++開發環境自然可以用,而用C++開發環境使用的方法在MFC一樣也可以使用。由於C++/MFC中使用類模板、CString類、String類等,使得解決這些問題的辦法很多,因此這裏主要介紹C開發環境中的方法。

 

一. 字符串轉化爲數字

C開發環境:主要使用atof  atoi  atol這三個函數。例子以及使用方法如下:

函數名: atof
功 能: 把字符串轉換成浮點數
用 法: double atof(const char *nptr);
程序例:
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
float f;
char *str = "12345.67";

f =atof(str);
printf("string = %s float = %f\n", str, f);
return 0;
}

函數名: atoi
功 能: 把字符串轉換成長整型數
用 法: int atoi(const char *nptr);
程序例:
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int n;
char *str = "12345.67";

n =atoi(str);
printf("string = %s integer = %d\n", str, n);
return 0;
}

函數名: atol
功 能: 把字符串轉換成長整型數
用 法: long atol(const char *nptr);
程序例:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
long l;
char *str = "98765432";

l = atol(lstr);
printf("string = %s integer = %ld\n", str, l);
return(0);
}

當然,也可以自己寫函數進行實現,而且一般程序員面試的時候很喜歡這種題目,函數以及相應的代碼如下:

 

int str2int(constchar *str)

{

    int itemp = 0;

    const char *ptr = str;  //ptr保存str字符串開頭

   

    //如果第一個字符是正負號,則移到下一個字符

    if (*str == '-' || *str == '+')

    {                          

       str++;

    }

   

    while(*str != 0)

    {

       //如果當前字符不是數字,則退出循環

       if ((*str < '0') || (*str > '9'))

       {                      

           break;

       }

       //如果當前字符是數字則計算數值,移到下一個字符

       itemp = itemp * 10 + (*str - '0');

       str++;     

    }

   

    //如果字符串是以"-"開頭,則轉換成其相反數

    if (*ptr == '-')   

    {

       itemp = -itemp;

    }

   

    return temp;

}

 

二. 數字轉化爲字符串(C開發環境)

    這裏的問題就比較簡單了,直接可以利用格式化輸入函數sprintf解決問題,也可以利用C中的庫函數itoa()。

    分別舉例如下:

 

char   str[10];

sprintf(str, "%d ",99);

 

函數名: itoa
功 能: 把一整數轉換爲字符串
用 法: char *itoa(int value, char *string, int radix);
程序例:

#include <stdlib.h>
#include <stdio.h>

int main(void)
{
int number = 12345;
char string[25];

itoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
return 0;

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章