c 標準庫數字與字元相互轉換

2021-09-04 02:01:48 字數 2432 閱讀 3212

1.字串轉數字

使用c++11引入的c++庫函式將string轉換為數值型別,相應的庫函式申明於標頭檔案中。

名稱    原型    說明

stoi    int stoi (const string& str, size_t* idx = 0, int base = 10);

int stoi (const wstring& str, size_t* idx = 0, int base = 10);    convert string to integer (function template )

stol    long stol (const string& str, size_t* idx = 0, int base = 10);

long stol (const wstring& str, size_t* idx = 0, int base = 10);    convert string to long int (function template)

stoul    unsigned long stoul (const string& str, size_t* idx = 0, int base = 10);

unsigned long stoul (const wstring& str, size_t* idx = 0, int base = 10);    convert string to unsigned integer (function template)

stoll    long long stoll (const string& str, size_t* idx = 0, int base = 10);

long long stoll (const wstring& str, size_t* idx = 0, int base = 10);    convert string to long long (function template)

stoull    unsigned long long stoull (const string& str, size_t* idx = 0, int base = 10);

unsigned long long stoull (const wstring& str, size_t* idx = 0, int base = 10);    convert string to unsigned long long (function template)

stof    float stof (const string& str, size_t* idx = 0);

float stof (const wstring& str, size_t* idx = 0);    convert string to float (function template )

stod    double stod (const string& str, size_t* idx = 0);

double stod (const wstring& str, size_t* idx = 0);    convert string to double (function template )

stold    long double stold (const string& str, size_t* idx = 0);

long double stold (const wstring& str, size_t* idx = 0);    convert string to long double (function template)

形參說明: 

str:過載了string和wstring版本,表示被轉換的字串。

idx:表示乙個size_t*的指標型別,預設為空值。不為空時,轉換成功時獲取第乙個非數值字元的下標。一般情況下,因為它是直接char型指標把最後非數值字元的位址值和起始位址值相減,所以也表示成功轉換的字元數量,如」10」轉成功為數值10時,*idx的值為2。

base:表示轉換基準,預設是10進製。

2.數字轉字串

std命令空間下有乙個c++標準庫函式std::to_string(),可用於將數值型別轉換為string。使用時需要include標頭檔案。

函式原型申明如下:

string to_string (int val);

string to_string (long val);

string to_string (long long val);

string to_string (unsigned val);

string to_string (unsigned long val);

string to_string (unsigned long long val);

string to_string (float val);

string to_string (double val);

string to_string (long double val);

c 數字與字串的相互轉換

首先推薦用用c 的stringstream。主要原因是操作簡單。數字轉字串,int float型別 同理 include include int main 字串轉數字,int float型別 同理 int main 上面方法的優點就是使用簡單方便,確定可能會相對別的方法來說慢一點,但是一般少量的資料...

c 數字與字串的相互轉換

首先推薦用用c 的stringstream。主要原因是操作簡單。數字轉字串,int float型別 同理 include include int main 字串轉數字,int float型別 同理 int main 上面方法的優點就是使用簡單方便,確定可能會相對別的方法來說慢一點,但是一般少量的資料...

c 數字與字串的相互轉換

首先推薦用用c 的stringstream。主要原因是操作簡單。0x00 字串轉數字 zcj 14.cpp 該程式是乙個序號產生器,原理是對輸入的字元每個與2求異或的結果取低位即為序號產生器。先輸入乙個字元陣列在轉化的int陣列再逐個與2求異或後儲存 include pch.h include in...