1. 程式人生 > 其它 >linux g++ 下C++ int,char,string 轉換注意

linux g++ 下C++ int,char,string 轉換注意

技術標籤:C/C++c++字串

int 與 char 互轉

說明:int與char的轉換是指依照ASCII字符集的對映關係轉換,很簡單c++預設的賦值就可以轉換;

貼一個簡單的測試程式

  3 #include <iostream>
  4 #include <typeinfo>
  5 #include <string>
  6 
  7 using namespace std;
  8 
  9 int main(int argi, char* argc[])
 10 {
 16         //int -- char
 17         int inta = 49;
 18         char chara='a';
 19         string stra = "98";
 20 
 21         char charb= inta;
 22         int intb = chara;
 23 
 24         //int -- string;
 25         string strc = to_string(inta);                            
 26         int intc = stoi(stra);
 27         
 28         cout <<"int 與 char 直接轉換 :"<<endl;
 29         cout <<"charb type : "<<typeid(charb).name() << "----值 :     "<<charb <<endl;
 30         cout <<"intb type : "<<typeid(intb).name() << "----值 : "<    <intb <<endl;
 31         cout <<"------------------------------------"<<endl;
 32 
 33         cout <<"int 與 string 型別轉換 : "<< endl;
 34         cout <<"strc type : "<<typeid(strc).name() << "----值 : "<    <strc <<endl;
 35         cout <<"intc type : "<<typeid(intc).name() <<"----值 : " <    <intc <<endl;
 36 
 37         return 0;
 38 }
//執行結果:
int 與 char 直接轉換 :
charb type : c----值 : 1
intb type : i----值 : 97
------------------------------------
int 與 string 型別轉換 : 
strc type : Ss----值 : 49
intc type : i----值 : 98

int 與 string 互轉方法有很多,這裡不介紹stringstream

簡單的說說在std空間中的to_string 和stoi兩函式的使用注意點:

首先.這兩函式都是C++11後支援的,所以要確保自己gcc++版本支援
其次.是即使gcc版本支援,預設編譯時也是用的c++98的版本,所以記得編譯時

帶上 “-std=c++11”,我這裡為了一勞永逸取了別名:alias g++11=“g++ -std=c++11”