阿拉伯數字int與string/char的轉換

阿拉伯數字int與string的轉換

string轉int

1)stoi()
需包含頭文件 #include < algorithm >

舉例

string str = "89";
int i = stoi(str);

2)atoi()
需包含頭文件 #include < cstdlib >
舉例

std::string text = "152"; 
int number = std::atoi( text.c_str() );

char轉int

瞭解int與char相互轉換之前,先讓我們看一下ASCII碼錶。
在這裏插入圖片描述
舉例

string s("123")
int a = s[1]-'0';
cout<<a;

輸出:2

int轉string

#include < string >
to_string()
舉例

string s = to_string(123);

stringstream

在C++標準庫裏面,使用stringstream,可以用於各種數據類型之間的轉換
需包含頭文件 #include < sstream >
舉例
stringstream ss;
int n = 123;
string str;
ss<<n;
ss>>str;

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