This blog is under construction

Tuesday 16 July 2013

C program to convert string to float without using atof

Write a C program to convert string to float without using atof.


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

  int main() {
        char input[32];
        int count = 0, num = 0, i;
        float val = 1.0, res = 0.0, tmp;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(input, 32, stdin);
        input[strlen(input) - 1] = '\0';


        /* check whether input is having invalid characters */
        for (i = 0; i < strlen(input); i++) {
                if (input[i] == '.' && count == 0) {
                        count++;
                        continue;
                }

                if (input[i] < '0' && input[i] > '9') {
                        printf("Wrong Input!!\n");
                        return 0;
                }
        }

        i = 0;

        /* manipulating the whole number first */
        while (input[i] != '.' && input[i] != '\0') {
                num = num * 10 + (input[i] - '0');
                i++;
        }

        /* skip the dot in input string *
        i++;

        /* decimal value manipulation - data after dot */
        while (count == 1 && input[i] != '\0') {
                val = val * 0.1;
                tmp = val * (input[i] - '0');
                res = res + tmp;
                i++;
        }

        /* add whole number and decimal value to get float value */
        res = res + num;

        /* print the result */
        printf("Result: %.3f\n", res);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string:1234.324
  Result: 1234.324


No comments:

Post a Comment