C atof() Function

The atof() function in C is a standard library function that converts a string to a double. It is part of the C standard library (stdlib.h) and is commonly used to convert string representations of floating-point numbers into their corresponding double values.

Table of Contents

  1. Introduction
  2. atof() Function Syntax
  3. Examples
    • Converting a Simple String to Double
    • Handling Invalid Input
  4. Real-World Use Case
  5. Conclusion

Introduction

The atof() function is useful for converting strings that represent floating-point numbers into double values. This function is essential when working with numerical data stored as strings.

atof() Function Syntax

The syntax for the atof() function is as follows:

double atof(const char *str);

Parameters:

  • str: A C string that contains the representation of a floating-point number.

Returns:

  • The function returns the converted double value. If no valid conversion could be performed, it returns 0.0.

Examples

Converting a Simple String to Double

To demonstrate how to use atof() to convert a string to a double, we will write a simple program.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *str = "123.45";
    double num;

    // Convert string to double
    num = atof(str);

    // Print the converted value
    printf("The converted value is: %f\n", num);

    return 0;
}

Output:

The converted value is: 123.450000

Handling Invalid Input

This example shows how atof() behaves with invalid input.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    const char *str = "abc123";
    double num;

    // Convert string to double
    num = atof(str);

    // Print the converted value
    printf("The converted value is: %f\n", num);

    return 0;
}

Output:

The converted value is: 0.000000

Real-World Use Case

Converting User Input to Double

In real-world applications, the atof() function can be used to convert user input, provided as a string, into a double for further numerical processing.

Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    char input[100];
    double value;

    // Prompt the user for input
    printf("Enter a floating-point number: ");
    fgets(input, sizeof(input), stdin);

    // Convert input to double
    value = atof(input);

    // Print the converted value
    printf("You entered: %f\n", value);

    return 0;
}

Output (example user input "45.67"):

Enter a floating-point number: 45.67
You entered: 45.670000

Conclusion

The atof() function is used for converting strings to double values in C. By understanding and using this function, you can effectively manage and process numerical data stored as strings in your C programs. Always handle invalid input scenarios to ensure robust applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top