提取整数
要求:输入一个字符串里面包含一个整数,注意字符串中可能有空格。
用字符串string
用char
提取整数
要求:输入一串字符串,里面包含若干个小数,字符串中可能有空格。
比如输入:The marathon runner completed the 10.5-kilometer race in under an hour, averaging a pace of 4.75 minutes per kilometer.;
遍历后转数值的写法
string s="The marathon runner completed the \
10.5-kilometer race in under an hour, \
averaging a pace of 4.75 minutes per kilometer."; //获取每一个数值
double num=0,xsw=0.1;
bool xs=false;
for(int i=0;i<s.size();++i){if(s[i]>='0' && s[i]<='9'){int c=s[i]-'0';if(xs==false){num=num*10+c;}else{num+=c*xsw;xsw/=10;}}else if(s[i]=='.'){xs=true;}else{if(num!=0){cout<<num<<endl;num=0;}xs=false;xsw=0.1;}
}
用stod
string s="The marathon runner completed the \
10.5-kilometer race in under an hour, \
averaging a pace of 4.75 minutes per kilometer."; string cn="";
for(int i=0;i<s.size();++i){if(s[i]>='0' && s[i]<='9' || s[i]=='.'){cn+=s[i];}else{if(cn.size()>0){cout<<stod(cn)<<endl;cn="";}}
}