Gehteuch Nixan
Gehteuch Nixan

Reputation: 29

How to convert a String to a Float in C

I have written the following code

#include <stdio.h>      
#include <stdlib.h> 
int main()

{
    // declaration of variables as strings
    char astr;
    char bstr;
    char cstr;

    /* Input three sides of a triangle */
    printf("Enter first side of triangle: ");
    scanf("%s",&astr);
    printf("Enter second side of triangle: ");
    scanf("%s",&bstr);
    printf("Enter third side of triangle: ");
    scanf("%s",&cstr);

    // conversion of strings to float
    float a = atof(&astr);
    float b = atof(&bstr);
    float c = atof(&cstr);
    // checking if given triangle is valid
    if((a + b > c) && (a + c > b) && (b + c > a))
    {
       // Checking for special cases of triangle

        if(a==b && b==c)
        {
            /* If all sides are equal */
            printf("Equilateral triangle.");
        }
        else if(a==b || a==c || b==c)
        {
            /* If any two sides are equal */
            printf("Isosceles triangle.");
        }
        else
        {
            /* If none sides are equal */
            printf("Scalene triangle.");
        }
    }
    else
    {
        printf("Triangle is not valid. \n");
    }

    printf("%f \n", a);
    printf("%f \n", b);
    printf("%f \n" ,c);
    return 0;
}

However when I run it, I get "Triangle is not valid" despite the fact that mathematically the triangle would be valid

When printing the Values stored in a b and c I discover that only the Value for c is stored correctly but a and b are always 0.000000

what have I done wrong?

Thanks in advance

Upvotes: 0

Views: 96

Answers (2)

Akshay Krishnan
Akshay Krishnan

Reputation: 1

int main () {
float val;
char str[10];
strcpy(str, "1234");
val = atof(str);
printf("%f", val);
return 0;
}

You can also use strtod() refer man page of atof()

Upvotes: -1

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140196

instead of 3 wrong lines:

char astr;
scanf("%s",&astr);
float a = atof(&astr);

let me propose working lines:

char astr[20];  // should be enough
scanf("%19s",astr);  // 19 protects from buffer overflow on astr
float a = atof(astr);

First, you cannot scan a string into a char: not enough room / undefined behaviour. Pass a char array instead (and in that case drop the &, it's already an address)

Second, pass the string to atof, not the pointer on the string.

Aside: atof doesn't check for errors, better use strtof which provides (optional) error checking.

Upvotes: 2

Related Questions