Jan 26, 2012

K & R C Programs Exercise 5-2.

K and R C, Solution to Exercise 5-2:
K and R C Programs Exercises provides the solution to all the exercises in the C Programming Language (2nd Edition). You can learn and solve K&R C Programs Exercise.
C Program to get next floating point analog of getint.The routine getfloat is similar to the routine getint. getfloat skips whitespaces, records the sign, and stores the integer part of the number at the address in fp.
getfloat also handles the practional part of the number(but not scientific notation). the fractional part is added to *fp in the same fashion as the integer part. Read more about C Programming Language .

/***********************************************************
* You can use all the programs on  www.c-program-example.com
* for personal and learning purposes. For permissions to use the
* programs for commercial purposes,
* contact info@c-program-example.com
* To find more C programs, do visit www.c-program-example.com
* and browse!
* 
*                      Happy Coding
***********************************************************/

#include<ctype.h>
#include<math.h>

int getfloat(float *fp)
{
 int ch;
 int sign;
 int fraction;
 int digits;

 while (isspace(ch = getch()))   /* skip white space */
  ;

 if (!isdigit(ch) && ch != EOF && ch != '+'
   && ch != '-' && ch != '.') {
  ungetch(ch);
  return 0;
 }

 sign = (ch == '-') ? -1 : 1;
 if (ch == '+' || ch == '-') {
  ch = getch();
  if (!isdigit(ch) && ch != '.') {
   if (ch == EOF) {
    return EOF;
   } else {
    ungetch(ch);
    return 0;
   }
  }
 }

 *fp = 0;
 fraction = 0;
 digits = 0;
 for ( ; isdigit(ch) || ch == '.' ; ch = getch()) {
  if (ch == '.') {
   fraction = 1;
  } else {
   if (!fraction) {
    *fp = 10 * *fp + (ch - '0');
   } else {
    *fp = *fp + ((ch - '0') / pow(10, fraction));
    fraction++;
   }
   digits++;
  }
 }

 *fp *= sign;

 if (ch == EOF) {
  return EOF;
 } else {
  ungetch(ch);
  return (digits) ? ch : 0;
 }
}

//for testing... try the different one!
#include<stdio.h>

int main(void)
{
 int ret;

 do {
  float f;

  fputs("Enter a number: ", stdout);
  fflush(stdout);
  ret = getfloat(&f);
  if (ret > 0) {
   printf("You entered: %f\n", f);
  }
 } while (ret > 0);

 if (ret == EOF) {
  puts("Stopped by EOF.");
 } else {
  puts("Stopped by bad input.");
 }

 return 0;
}



Read more Similar C Programs
C Basic
C Strings
K and R C Programs Exercise
You can easily select the code by double clicking on the code area above.

To get regular updates on new C programs, you can

You can discuss these programs on our Facebook Page. Start a discussion right now,

our page!

Share this program with your Facebook friends now! by liking it


(you can send this program to your friend using this button)

Like to get updates right inside your feed reader? Grab our feed!


To browse more C Programs visit this link