http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=96&page=show_problem&problem=478
题意:
输入一道数学题,有一定格式,**U=200V**I=4.5A**
抽出U和I,求P。也可能是求U或I
解题:
用string + istringstream 分离数字和字符串,简单好多。
istringsream是个好东西,可以分离字符串,也可以用来做类型转换。从int到string,从char*到str之类的。
中间使用了整形指针。。。突然觉得有些东西(如整型指针)学了,用时才不会恨学得少;学习知识就是潜在应用。
有时又要求最后一行不能加回车,有时不加又WA。真奇葩。。。。
#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <stdio.h>
using namespace std;
int main()
{
int nCase;
cin >>nCase;
cin.ignore();
string s1, s2, s3;
for ( int index=1; index <= nCase; index++ )
{
getline(cin, s1, '=');
getline(cin, s2, '=');
getline(cin, s3);
// get d2 of section s2
istringstream strStream(s2);
double d2;
string s2Remain;
strStream >>d2;
strStream >>s2Remain;
// get d3 of section s3
strStream.str(s3);
double d3;
string s3Remain;
strStream >>d3;
strStream >>s3Remain;
double numP = 0.0;
double numU = 0.0;
double numI = 0.0;
double *pNum;
switch ( s1[s1.length()-1] )
{
case 'P':
pNum = &numP;
break;
case 'U':
pNum = &numU;
break;
case 'I':
pNum = &numI;
break;
}
*pNum = d2;
switch ( s2Remain[0] )
{
case 'm':
*pNum /= 1000;
break;
case 'k':
*pNum *= 1000;
break;
case 'M':
*pNum *= 1000000;
break;
}
switch ( s2[s2.length()-1] )
{
case 'P':
pNum = &numP;
break;
case 'U':
pNum = &numU;
break;
case 'I':
pNum = &numI;
break;
}
*pNum = d3;
switch ( s3Remain[0] )
{
case 'm':
*pNum /= 1000;
break;
case 'k':
*pNum *= 1000;
break;
case 'M':
*pNum *= 1000000;
break;
}
cout <<"Problem #" <<index <<'\n';
if ( numP == 0 )
{
cout <<"P=";
cout <<fixed <<setprecision(2) <<numU*numI <<"W\n";
} // end if
else
{
if ( numU == 0 )
{
cout <<"U=";
cout <<fixed <<setprecision(2) <<numP/numI <<"V\n";
} // end if
else
{
cout <<"I=";
cout <<fixed <<setprecision(2) <<numP/numU <<"A\n";
} // end else
} // end else
cout <<'\n';
} // end for
return 0;
}