C++中將string類型轉化為int類型

來源:互聯網
上載者:User

標籤:ring   log   clu   images   c_str   需要   程式   alt   and   

  寫程式需要將string轉化為int,所以就探索了一下。

  方法一:atoi函數

  atoi函數將字串轉化為整數,注意需要stdlib庫。所以就嘗試了一下:

  

 1 #include <iostream> 2 #include <string.h> 3 #include <stdlib.h> 4 using namespace std; 5 int main() 6 { 7     string a="11",b="22"; 8     cout<<atoi(a)+atoi(b)<<endl; 9     return 0;10 11 }

  然而卻發現報錯:

  

  顯然,atoi需要的事const char*類型,而我上面給的上string類型,所以就要 多加一個函數string.c_str()。string.c_str是Borland封裝的String類中的一個函數,它返回當前字串的首字元地址。

  c_str函數的傳回值是const char*,所以我們加上c_str()函數:

 

#include <iostream>#include <string.h>#include <stdlib.h>using namespace std;int main(){    string a="11",b="22";    cout<<atoi(a.c_str())+atoi(b.c_str())<<endl;    return 0;}

  然後就成功了,有什麼不妥的希望大家指出。

 

  

  

C++中將string類型轉化為int類型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.