一、string转int
由于int所能表示有限,1、2方法只适用于短string。
3方法可引进carry借位,从个位按位相加减,直接输出string,因此可计算长string。
方法1:
<span style="font-size:18px;">using namespace std;
void main()
{
//string转char数组
<pre name="code" class="cpp"> <span style="font-family: Arial, Helvetica, sans-serif;">string a="152342";</span>
<span style="font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="cpp"> <span style="font-family: Arial, Helvetica, sans-serif;">char num[100];</span>
<span lang="EN-US" style="font-size: 7.5pt; font-family: 'Times New Roman';"> </span><span style="font-family: Arial, Helvetica, sans-serif;">strcpy(num,a.c_str());</span>
<span style="white-space:pre"> </span>cout<<num<<"\n";//char数组转int<span style="white-space:pre"> </span>int c;<span style="white-space:pre"> </span>c=strtol(num,NULL,10);<span style="white-space:pre"> </span>cout<<c;<span style="white-space:pre"> </span>getchar();}</span>
方法2:
<span style="font-size:18px;">using namespace std;
void main()
{
<span style="white-space:pre"> </span>int c=0;
<span style="white-space:pre"> </span>string a="152312";
<span style="white-space:pre"> </span>for(int i=0;i<a.length();i++)
<span style="white-space:pre"> </span>{
<span style="white-space:pre"> </span>c=c*10+(a[i]-'0');
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>cout<<c;
<span style="white-space:pre"> </span>getchar();
}</span>
方法3:
<pre name="code" class="cpp"><span style="font-size:18px;">using namespace std;
void main()
{ string a="1832932";
int lena = a.size();
int current=0;
for(int i=lena-1;i>=0;i--)
{
<span style="white-space:pre"> </span>current+=(a[i]-'0')*pow((double)10,(lena-i-1));
}
cout<<current;
getchar();
}</span>