您的位置:首页 > 其它

字符串中如何提取数值

2014-04-09 09:20 267 查看
给一段字符串,如何在给定的字符串中提取出相应的数值,并运用这些数值;

可以使用 getchar() 找到特殊字符 , 然后把相应的数值存入一个字符数组中,最后在字符数组的最后一位加上'\0'(字符串结束标志),然后字符数组中的字符转换成数值,可以使用sscanf(s,"%lf",&a) 也可以使用atof(s) ;两种方法效果相同;

具体解法如下:

#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
using namespace std ;

char a[105] , aa ;
char flag ;
void getss(char *s)	{
int i = 0 ;
for(;i < 100 ; i++)	{
s[i] = getchar() ;
if(s[i] == '=')	{
int j = 0 ;
for(++i ; i < 100 ; i++,j++)	{
s[i] = getchar() ;
if((s[i] == 'm' || s[i] == 'M' || s[i] == 'k'))	{
s[++i] = getchar() ;
if(s[i] == 'A'||s[i] == 'V'||s[i] == 'W')	{
flag = s[i-1] ;
}
}
a[j] = s[i] ;
if(a[j] == '.')
continue ;
if(a[j] < '0' || a[j] > '9')	{
a[j] = '\0' ;
aa = s[i] ;
break ;
}
}
break ;
}
}
}

int main()	{
int n ;
cin >> n ;
getchar() ;
int t = 1 ;
while(n--)	{
char s1[105] , s2[105]  , s3[105] ;
double x , y ;
flag = 'e';
getss(s1) ;
char a1[105] , a2 = aa ;
strcpy(a1,a);
x = atof(a1) ;
if(flag == 'm')
x /= 1000 ;
else if(flag == 'k')
x *= 1000 ;
else if(flag == 'M')
x *= 1000000 ;
flag = 'e' ;
getss(s2) ;
char b1[105] , b2 = aa ;
strcpy(b1,a) ;
sscanf(b1,"%lf",&y) ;

if(flag == 'm')
y /= 1000 ;
else if(flag == 'k')
y *= 1000 ;
else if(flag == 'M')
y *= 1000000 ;

gets(s3) ;

cout << "Problem #" << t++ << endl ;
if(a2 == 'A' && b2 == 'W')
printf("U=%.2lfV\n",double(y*1.0/x)) ;
else if(a2 == 'W' && b2 == 'A')
printf("U=%.2lfV\n",double(x*1.0/y)) ;
else if(a2 == 'V' && b2 == 'W')
printf("I=%.2lfA\n",double(y*1.0/x)) ;
else if(a2 == 'W' && b2 == 'V')
printf("I=%.2lfA\n",double(x*1.0/y)) ;
else if(a2 == 'V' && b2 == 'A' || a2 == 'A' && b2 == 'V')
printf("P=%.2lfW\n",double(y*1.0*x)) ;
cout << endl ;

}
return 0 ;
}


在网上也发现一些其他方法解决了此题,下面介绍一种方法,从中学到一些:

头文件 #include<sstream>

char s[100] ;

gets(s) ;

istringstream sin(s) ;

double d ;

int i = 0 ;

char s1 ;

while(sin>> s1)  {

if(s1>='0'&&s1 <= '9')

  sin >> d ;

}

变量d中存放的就是字符类型对应的数值类型

#include<iostream>
#include<sstream>
#include<string>
#include<cstdio>
using namespace std;

int main()
{
/*
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
//*/

int T;
cin>>T;getchar();
for(int case_num=1;case_num<=T;case_num++)
{
string line;
getline(cin,line);
double P(-1.0),U(-1.0),I(-1.0);
istringstream sin(line);
char ch;
while(sin>>ch)
{
if(ch=='P')
{
char t;
sin>>t;
if(t!='=')
continue;
sin>>P;
sin>>t;
if(t=='m')
P/=1000;
else if(t=='k')
P*=1000;
else if(t=='M')
P*=1000000;
}
else if(ch=='U')
{
char t;
sin>>t;
if(t!='=')
continue;
sin>>U;
sin>>t;
if(t=='m')
U/=1000;
else if(t=='k')
U*=1000;
else if(t=='M')
U*=1000000;
}
else if(ch=='I')
{
char t;
sin>>t;
if(t!='=')
continue;
sin>>I;
sin>>t;
if(t=='m')
I/=1000;
else if(t=='k')
I*=1000;
else if(t=='M')
I*=1000000;
}
}

cout<<"Problem #"<<case_num<<endl;
if(P==-1.0)
printf("P=%.2fW\n",U*I);
else if(U==-1.0)
printf("U=%.2fV\n",P/I);
else
printf("I=%.2fA\n",P/U);
printf("\n");
}

return 0;
}


istringstream 用起来确实比较方便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: