c++中int與char,string的相互轉換

1.ASCLL表

 

這裏我們主要關注的是0-9對應的ASCLL碼值爲48-57.

2.char轉int

在char類型字符相減時,結果會自動轉爲int型:

char a = '1';
cout << typeid(a - '0').name() << endl;
cout << a - '0' << endl;

輸出就爲int,1

如果是char類型減去數字,結果也是int類型:

char a = '1';
cout << typeid(a - 0).name() << endl;
cout << a - '0' << endl;

輸出爲int,47。即直接將'a'轉爲爲對應的ASCLL碼做計算。

3.int轉char

int a = 1;
char b = a + '0';
cout << typeid(a +'0').name() << endl;
cout << b << endl;

a+'0'爲int類型,對應的時a和'0'的ASCLL碼相加,賦值給char類型的b就自動轉爲char類型。

輸出爲int,1(這裏的1爲字符)。


4.int轉string

上面我們只討論了0-9的數字轉char,那如果是12394這樣的數呢?

首先這肯定不是int轉char,那int轉string怎麼做呢?我這裏也隨便寫了一下(記得#include<string>哦):

int a = 12394;
string s;
//這裏爲了裝逼將for循環融到一行裏了,乍一看有點厲害,仔細看也就那樣
for (int k=a%10; a > 0; a /= 10, k = a % 10) s.push_back(k+'0');
reverse(s.begin(), s.end());
cout << s << endl;

輸出爲string類型的12394。

在寫上面程序第二天我發現了to_string。。。

string s = to_string(a);//將整數a轉換爲字符型

5.string轉int

int stoi (const string&  str, size_t* idx = 0, int base = 10);
//str爲字符串,idx爲字符串中指向數值後面的下一位元素的指針,base爲字符串的進制
// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

輸出:

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