C string和int型別的轉換方法

2021-07-25 02:26:35 字數 740 閱讀 6444

總結一下c++中string和int的兩種轉換方法。

第一種:使用c標準庫中的函式atoi()和itoa():

#include #include using namespace std;

int main()

注意在這個方法中vs中會報告出現不安全,在配置屬性->c/c++->預處理器加入_crt_secure_no_warnings可以消除該警報。

第二種,使用stringstream是一種比較推薦的方法,可以用來實現string和其他型別的轉換。

#include #include #include using namespace std;

int main()

第三種使用sprintf和sscanf,這兩個函式是用來做字元陣列和整數的轉換的,然後在轉換成為string。

#include #include using namespace std;

int main()

第四中從c++11以後標準庫中提供了stoi和to_string方法,可以很方便的進行轉換。

#include #include using namespace std;

int _tmain(int argc, _tchar* argv)

C string轉int的方法

一 點睛 需要用到下面這一組函式。long int strtol const char nptr,char endptr,int base 將引數nptr字串根據引數base來轉換成有符號的整型 long long int strtoll const char nptr,char endptr,in...

Date型別轉int型別

由於有些mysql資料庫中儲存的是int型別,所以進行條件篩選時需要進行處理。將需要的日期轉換為int型別進行比較。date型別轉int型別 integer date integer.valueof string.valueof new date gettime substring 0,10 int...

CString型別轉char型別出現中文亂碼問題

一般來說cstring型別的變數具有很強的操作性,但有時為了使用某些c函式,必須將cstring型別的變數轉換為char陣列型別。關於cstring轉char的方法,網上查了查,發現大都沒介紹清楚,這裡寫出來做個小結,加深下印象。為完成他們之間的轉換,首先得說明一下他們所佔的記憶體大小。cstrin...