题目:https://vjudge.net/problem/UVA-1586
#include <bits/stdc++.h>
using namespace std;
int main(){
int num = 0;
cin >> num;
map<char, double> map;
map['C'] = 12.01;
map['H'] = 1.008;
map['O']= 16.00;
map['N'] = 14.01;
while (num--)
{
string s;
cin >> s;
int len = s.size();
double mass = 0.0;
for (int i = 0; i < len;i++){
if(isdigit(s[i]))
continue;
double a = map[s[i]];
int cn = 1;
if(i+2<len && isdigit(s[i+1]) && isdigit(s[i+2])){ //如果有两个数字,就读取两个数字
cn = (s[i + 1] - '0') * 10 + (s[i + 2] - '0');
}else if(i+1<len && isdigit(s[i+1])){ //一个数字就读取一个,不要用while,因为限制了下标范围2-99
cn = s[i + 1] - '0';
}
mass += a*cn;
}
cout << mass <<endl;
}
// system("pause");
return 0;
}
bool isdigit(char ch)判断字符是否为数字。
更多cctype函数