C和C 中字串與數的轉換

2022-03-11 03:17:28 字數 2797 閱讀 4963

以下內容來自《c/c++程式設計實用案例教程》

1、在c語言中的轉換方式

1.1數字轉換為字串

在c語言中,sprintf函式可以將任何多個數字格式化為指定格式的字串,sprintf函式宣告如下

int sprintf(char* buffer,const char* format,...);
可以看出和printf的函式宣告很相似

int printf(const char* format,...);
但是它多了第乙個引數buffer,因為printf只需要將格式化的內容輸出到console視窗,而sprintf需要將格式化的內容輸出到緩衝區,buffer就是這個緩衝區記憶體。

因為是輸出到緩衝區,所以報自行確保str的記憶體空間足夠容納格式化的內容,否則存在內容溢位的風險,乙個null字元會被自動新增到格式化內容的最後位置。

函式的int型別的返回值返回的是字串的長度(不包括字串最後的空字元)。

1.1例子

#include #pragma warning(disable:4996)

int main()

1.1結果

1.2從字串中提取數字

c語言提供了sscanf函式用於從格式化的字串中提取多個型別的資料,同理,sscanf和scanf的作用類似,區別在於scanf是從使用者鍵盤輸入的字元中提取資料,而sscanf是從乙個字串緩衝區中提取資料,sscanf函式宣告如下:

int sscanf(const char* buffer, const char* format,...);
1.2例子

#include #pragma warning(disable:4996)

int main()

1.2結果 

1.3字串轉換為整數

在c語言中,將字串變為乙個整數,可以使用atoi函式,需要引入標頭檔案,atoi函式宣告如下

int atoi (const char* str);
1.3例子

#include #include #pragma warning(disable:4996)

int main()

1.3結果

1.4字串轉換為浮點數

將字串轉換為浮點數,可以使用atof函式,atof函式宣告如下

double atof(const char* str);
1.4例子

#include #include #pragma warning(disable:4996)

int main()

1.4結果

2、在c++中的轉換方式

在c++中,std::string類沒有提供任何字串與數字轉換的方法,這個任務交給了stringstream類。

2.1將字串轉換為數字

想把字串轉換為數字,使用istringstream類,需要引入標頭檔案

2.1例子

#include #include //std::istringstream

#include //std::string

int main()

2.1錯誤寫法所導致的結果

2.1正確寫法的結果

2.2將數字轉換成字串

想把數字轉換成字串,使用ostringstream類,同樣需要引入標頭檔案

2.2例子

#include #include //std::ostringstream

#include //std::string

int main()

2.2結果

3、使用stl標準的庫函式std::stoi,std::stof和std::stod從std::string物件獲得int,float和double的值

函式宣告如下

int stoi(const string& _str, size_t *_idx = 0, int _base = 10);

float stof(const string& _str, size_t *_idx = 0);

double stod(const string& _str, size_t *_idx = 0);  //第二個引數返回的是字串中緊挨著數字的下乙個字元的索引

3.例子

#include //std::cout

#include //std::string std::stoi std::stod

int main()

3結果

4、拓展

C和C 中的字串與數字轉換函式

前言 今天開始想要好好補補程式,開始看老早就買了的 演算法入門經典 發現前面幾章對字串的處理較多,蒐羅了一下別人的部落格,整理到這上面來。c語言中常用的字串和數字轉換函式是sscanf和sprintf,c 中引入了流的概念,通過流來轉換字串和數字就方便了許多。sprintf函式原型為 int spr...

C 中數字與字串的轉換

1 字串數字之間的轉換 1 string char string str ok char p str.c str 2 char string char p ok string str p 3 char cstring char p ok cstring m str p 或者 cstring m st...

C 中整數和字元 字串的轉換

1 整數與字元的轉換 1 整數轉換為字元 整數加 0 就會隱性的轉換為char型別的數。2 字元轉換為整數 相反的,字元減去 0 就會轉換為整數。2 整數和字串的轉換 1 整數轉換為字串 使用itoa函式 例如 int num 12345 char str 10 itoa num,str,10 將n...