Ronald_mcd
Member
disclaimer - I am very new to C.
I am making a program that will split a chemical up into its elements, then find the molar mass of the chemical. Right now I am able to split it up into tokens (ie, split 2NaCl into 2, Na, and Cl.) My problem is when I have something like CH3COOH and one of my tokens is H3, I don't know how to split them up so I can multiply the H(1.01) by the 3.
my code so far.
I am making a program that will split a chemical up into its elements, then find the molar mass of the chemical. Right now I am able to split it up into tokens (ie, split 2NaCl into 2, Na, and Cl.) My problem is when I have something like CH3COOH and one of my tokens is H3, I don't know how to split them up so I can multiply the H(1.01) by the 3.
my code so far.
Code:
#include <ctype.h>
#include <stdio.h>
char *GetToken(char sFormula[], int *iStartPos, int iLength)
{
int iRetValue=0;
int iIndex=0;
static char sTempString[80];
if(isupper(sFormula[*iStartPos]))
{
do
{
sTempString[iIndex]=sFormula[*iStartPos];
(*iStartPos)++;
iIndex++;
}while(!(isupper(sFormula[*iStartPos])));
sTempString[iIndex]='\0';
}
return sTempString;
}
int GetNumber(char sFormula[], int *iStartPos, int iLength)
{
int iRetValue=1;
int iIndex=0;
char sTempString[80];
if(isdigit(sFormula[*iStartPos]))
{
do
{
sTempString[iIndex]=sFormula[*iStartPos];
(*iStartPos)++;
iIndex++;
}while(isdigit(sFormula[*iStartPos]));
sTempString[iIndex]='\0';
iRetValue=atoi(sTempString);
}
return iRetValue;
}
int main()
{
char sFormula[80];
char sToken[80];
int iOverAllMultiplier;
int iIndex, iLength;
printf("Enter the Chemical Formula\n");
gets(sFormula);
iLength=strlen(sFormula);
for (iIndex=0; iIndex<iLength;iIndex++)
{
if ((sFormula[iIndex]=='+') || (sFormula[iIndex]=='=') || (sFormula[iIndex]==' '))
break;
}
sFormula[iIndex]='\0';
iLength=iIndex;
iIndex=0 ;
iOverAllMultiplier=GetNumber(sFormula, &iIndex, iLength);
printf("Overall multiplier is %d\n ", iOverAllMultiplier);
while (iIndex<iLength)
{
strcpy(sToken, GetToken(sFormula, &iIndex, iLength));
printf("our token is : %s\n ", sToken);
}
system("PAUSE");
return 0;
}