int與string互轉

來源:互聯網
上載者:User

標籤:style   blog   os   io   使用   strong   ar   資料   div   

一  int轉string

第一種方法:

#include <iostream>
#include <string>
using namespace std;

int main()
{
int n = 65535;
char t[256];
string s;

sprintf(t, "%d", n);
s = t;
cout << s << endl;

return 0;
}

第二種方法:

#include <iostream>
#include <string>
#include <strstream>
using namespace std;

int main()
{
int n = 65535;
strstream ss;
string s;
ss << n;
ss >> s;
cout << s << endl;

return 0;
}

第三種方法:

//char *itoa( int value, char *string,int radix);
// 原型說明:
// value:欲轉換的資料。
// string:目標字串的地址。
// radix:轉換後的進位數,可以是10進位、16進位等。
// 返回指向string這個字串的指標

int aa = 30;
char c[8];
itoa(aa,c,16);
cout<<c<<endl; // 1e

第四種方法:

使用boost庫中的lexical_cast

int aa = 30;string s = boost::lexical_cast<string>(aa);cout<<s<<endl; // 30

二  string轉化為int
1、使用strtol(string to long) 

1 string s = "17";2  char* end;3  int i = static_cast<int>(strtol(s.c_str(),&end,16));4  cout<<i<<endl; // 235 6  i = static_cast<int>(strtol(s.c_str(),&end,10));7  cout<<i<<endl; // 17

2、使用sscanf

1 int i;2  sscanf("17","%D",&i);3  cout<<i<<endl; // 174 5  sscanf("17","%X",&i);6  cout<<i<<endl; // 237 8  sscanf("0X17","%X",&i);9  cout<<i<<endl; // 23

3、使用stringstream

1  string s = "17";2 3  stringstream ss;4  ss<<s;5 6  int i;7  ss>>i;8  cout<<i<<endl; // 17

註:stringstream可以吞下任何類型,根據實際需要吐出不同的類型。
4、使用boost庫中的lexical_cast

1  string s = "17";2  int i = boost::lexical_cast<int>(s);3  cout<<i<<endl; // 17

int與string互轉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.