我试图制作一个小函数,将整数和浮点数转换为字符串,将它们保存为双精度类型,一切正常,但是当我在逗号后面输入许多数字时,出现问题。
#include <iostream>
#include <cmath>
using namespace std;
/////////////////////////////////////CONVERTer FUNCTION/////////
double StrToNum(string InStr)
{
int a=0;
double b,OutInt=0,DecVal=0,DoubleOut;
for(a;a<=InStr.length();a++)
{
if(InStr[a]=='.' || InStr[a]==','){break;}
if(InStr[a]=='0'){OutInt=OutInt*10+0;}
if(InStr[a]=='1'){OutInt=OutInt*10+1;}
if(InStr[a]=='2'){OutInt=OutInt*10+2;}
if(InStr[a]=='3'){OutInt=OutInt*10+3;}
if(InStr[a]=='4'){OutInt=OutInt*10+4;}
if(InStr[a]=='5'){OutInt=OutInt*10+5;}
if(InStr[a]=='6'){OutInt=OutInt*10+6;}
if(InStr[a]=='7'){OutInt=OutInt*10+7;}
if(InStr[a]=='8'){OutInt=OutInt*10+8;}
if(InStr[a]=='9'){OutInt=OutInt*10+9;}
}
for(a=0;a<=InStr.length();a++)
{
if(InStr[a]=='.' || InStr[a]==','){a+=1; b=1; break;}
}
for(a;a<=InStr.length();a++)
{
if(InStr[a]=='0'){ b+=1;}
if(InStr[a]=='1'){DecVal=DecVal+1/pow(10,b); b+=1;}
if(InStr[a]=='2'){DecVal=DecVal+2/pow(10,b); b+=1;}
if(InStr[a]=='3'){DecVal=DecVal+3/pow(10,b); b+=1;}
if(InStr[a]=='4'){DecVal=DecVal+4/pow(10,b); b+=1;}
if(InStr[a]=='5'){DecVal=DecVal+5/pow(10,b); b+=1;}
if(InStr[a]=='6'){DecVal=DecVal+6/pow(10,b); b+=1;}
if(InStr[a]=='7'){DecVal=DecVal+7/pow(10,b); b+=1;}
if(InStr[a]=='8'){DecVal=DecVal+8/pow(10,b); b+=1;}
if(InStr[a]=='9'){DecVal=DecVal+9/pow(10,b); b+=1;}
}
DoubleOut=OutInt+DecVal;
return DoubleOut;
}
/////////////////////////////////////CONVERTer FUNCTION/////////
int main ()
{
string InStr;
double DoubleOut;
cout<<"Please input number(will be saved as string)"<<endl;
cin>>InStr;
DoubleOut=StrToNum(InStr);
cout<<"Integer converted from string= "<<DoubleOut<<endl;
system("PAUSE");
return 0;
}