#include<stdio.h>
#include<ctype.h>
#include<string.h>
int search(char *a,char (*b)[3]);
void main()
{
char a[10],temp[3],b[10][3]={"H","C","N","O","S","Na","Al","Cl","Ca","Zn"};
int m[11]={1,12,14,16,32,23,27,35,40,65};
int i=0,sum=0;
printf("输入化学式\n");
gets(a);
while(a[i]!='\0')
{
temp[0]=a[i];
i++;
if(isalpha(a[i]))//第二个字符是字母
{
temp[1]=a[i];
if(search(temp,b)!=-1)//俩字母是整体
{
i++;
if(isdigit(a[i]))//第三个字符是数字
sum+=m[(search(temp,b))]*(a[i]-'0');
else//第三个字符不是数字
{
sum+=m[search(temp,b)];
i--;
}
}
else//不是整体
{
temp[1]='\0';
i--;
sum+=m[search(temp,b)];
}
}
else//第二个字符不是字母
{
if(a[i]!='\0')
sum+=(a[i]-'0')*m[search(temp,b)];
else
{
sum+=m[search(temp,b)];
i--;
}
}
i++;
temp[0]=temp[1]='\0';
}
printf("%d\n",sum); /*char a[3]="O",b[10][3]={"H","C","N","O","S","Na","Al","Cl","Ca","Zn"};
int m[11]={1,12,14,16,32,23,27,35,40,65};
printf("%d\n",m[search(a,b)]);*/
}
int search(char *a,char (*b)[3])
{
int i;
for(i=0;i<10;i++)
{
if(strcmp(a,*(b+i))==0)
return i;
}
return -1;
}