C++中string與int的相互轉(zhuǎn)換實現(xiàn)代碼
更新時間:2017年05月21日 13:29:22 投稿:mdxy-dxy
這篇文章主要介紹了C++中string與int的相互轉(zhuǎn)換實現(xiàn)代碼,需要的朋友可以參考下
做ACM時,經(jīng)常用到string和int的轉(zhuǎn)換,下面的程序:
核心代碼:
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
/////////////////////////// string 轉(zhuǎn)為 int
string str="1234";
int n;
istringstream iss;//istringstream從string讀入,和cin一樣僅僅重載了>>,可以把string轉(zhuǎn)為int
iss.clear();//每次使用前先清空
iss.str(str);
iss>>n;//將輸入流中的內(nèi)容寫入到int n,
cout<<n<<endl;
//////////////////////////////// int 轉(zhuǎn)為 string
n=111;
ostringstream oss;//用于向string寫入,和cout<<一樣,僅僅重載了<<
oss<<n;
str=oss.str();
cout<<str<<endl;
///////////////////////////////// string 轉(zhuǎn)為 int
str="22222";
sscanf(str.c_str(),"%d",&n); //scanf前面加s用于把str輸入到n中
cout<<n<<endl;
/////////////////////////////// int 轉(zhuǎn)為 string
int ss=1000;
char temp[64];
sprintf(temp,"%d",ss); //printf前面加s用于將ss按整數(shù)形式輸出到數(shù)組temp中,不能直接給str.c_str();
str=temp;//再把數(shù)組temp賦值給str;
cout<<str<<endl;
return 0;
}
相關(guān)文章
OpenCV實戰(zhàn)之基于Hu矩實現(xiàn)輪廓匹配
這篇文章主要介紹了利用C++ OpenCV實現(xiàn)基于Hu矩的輪廓匹配,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)OpenCV有一定的幫助,感興趣的可以學(xué)習(xí)一下2022-01-01
C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn)
這篇文章主要介紹了C語言字符串函數(shù),字符函數(shù),內(nèi)存函數(shù)使用及模擬實現(xiàn),文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
C++實現(xiàn)LeetCode(146.近最少使用頁面置換緩存器)
這篇文章主要介紹了C++實現(xiàn)LeetCode(146.近最少使用頁面置換緩存器),本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

