// Proj2.cpp
// by Jason Plumb
// Concepts of Programming Languages
// Instructor:  Dr. Cooke
//
// Description:  This program will input an arbitrary string of characters
// and will convert the number into a floating point representation of the
// character string.  It should be noted that this program does not use
// any string conversion routines (such as strtol).  This program uses the
// type "double" to store all floating point values, so the value entered
// by the user should be in the range of "double".  It should also be noted
// that the two last lines of program output display the number in its floating
// point representation and the number + 3.1415.  The display of the final number
// (intput number + 3.1415) may not properly reflect the result due to floating
// point arithmetic inaccuracies.  This is not due to any flaw in the input
// string parsing program.  This program does not properly handle negative
// numbers, and there is no error checking to ensure that the number entered
// is a valid base 10 number.

// This file was compiled under Visual C++ 5.0

#include <stdio.h>
#include <string.h>
#include <math.h>

void main(){

 char buffer[200];
 char *pInt;        //Pointer to int portion
 char *pFrac;       //Pointer to the fractional portion
 long iInt, iFrac;
 int i, iLen;
 double fFrac, fAns;
 long exp;

 memset(buffer, NULL, 200);
 iFrac = iInt = 0;
 
 printf("Please enter a string to be converted to floating point:  ");

 gets(buffer);
 if(strlen(buffer)==0){
  printf("Nothing given...aborting!");
  return;
 }//if

 printf("The string entered was '%s'\n", buffer);
 pFrac = strchr(buffer, '.');

 if(pFrac==NULL){
  printf("No fractional portion was given...\n");
  printf("The fractional portion is 0\n");
  fFrac = 0;
 }//if
 else{

  pFrac++;   //Increment pointer over the '.' character
  iLen = strlen(pFrac);
  for(i=0;i<iLen;i++){
   exp = (long)pow(10,iLen-i-1);
   iFrac += (exp*(pFrac[i]-48));
  }//for
  printf("The fractional portion is:  %d * 10^-%d\n", iFrac, strlen(pFrac));
 }//else (fractional portion given)

 pInt = strtok(buffer, ".\r\n");  //Get portion before the '.'
 if(pInt==pFrac){      //If the int portion same as fraction
  printf("No integer portion given...\n");
 }//if
 else{
  iLen = strlen(pInt);
  for(i=0;i<iLen;i++){
   exp = (long)pow(10,iLen-i-1);
   iInt += (exp*(pInt[i]-48));
  }//for
 }//else (int portion given)
 printf("The integer portion is:  %d\n", iInt);

 if(fFrac!=0)
  fFrac = (double)(((double)iFrac)/(pow(10,strlen(pFrac))));

 fAns = iInt + fFrac;   //The result is the integer portion plus the fractional portion
 printf("The floating point number is %.15f\n", fAns);
 fAns += (double)3.1415;
 printf("The floating point number + 3.1415 is %.15f\n", fAns);

}//main