Convert a Char Array to Double in C
Last Updated :
21 May, 2023
Converting a char array to a double is a common operation in C programming. It involves taking a string of characters that represent a numerical value and converting it to a double-precision floating-point value. This can be done by using various approaches listed below:
Convert char array into double
Methods to convert the char array into double are mentioned below:
- atof() Function
- strtod() Function
- sscanf() Function
1. Using atof() function
atof() is a standard library function in C that converts a string of characters representing a floating-point number to its equivalent double-precision floating-point number. The atof() function is included in the stdlib.h library and takes a string as its argument. It then returns the floating-point value (double) equivalent of the string.
Syntax:
double atof(const char *str);
Where str is the string representation of the floating-point number to be converted.
Example 1: Converting char "3.14" to a double
In the given code, a character array chr[] is initialized with the string "3.14". Then, the atof() function is called with chr as its argument and the resulting double value is stored in the num variable. Finally, the converted value is printed using the printf() function.
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Define a character array chr containing the string
// "3.14"
char chr[] = "3.14";
// Convert the string to a double and store it in the
// variable num using the atof function
double num = atof(chr);
// Print the converted double value using printf
// function
printf("The converted double is: %f", num);
return 0;
}
OutputThe converted double is: 3.140000
2. Using strtod() function
strtod() is a standard C library function that converts a string to a double-precision floating-point number. It takes two arguments: the first argument is the string to convert, and the second argument is a pointer to a character string that points to the first character of a string of characters. This pointer is used to store the remaining characters after the conversion. The strtod() function provides greater precision and can handle a wider range of values compared to atof(). strtod() can handle long double values.
Syntax:
double strtod(const char *str, char **endptr);
Here, str is the string to be converted to a double-precision floating-point number, and endptr is a pointer to a character pointer. endptr is used to store the pointer to the first character after the numeric value in the string. If str does not contain a valid floating-point number, then endptr is set to str. If the string represents a valid floating-point number, then endptr points to the first character following the floating-point number.
Example 1:
In this example, we define a character array chr[] that contains the string "3.14" and a character pointer endptr that will be used to store the pointer to the first character after the numeric value in the string. We then call strtod() with chr and endptr as arguments to convert the string to a double. If the conversion is successful, we print the converted double value. If the conversion fails, it will print an error message.
C
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Define a character array chr containing the string
// "3.14"
char chr[] = "3.14";
// Define a character pointer endptr to be used with the
// strtod function
char* endptr;
// Convert the string to a double and store it in the
// variable num using the strtod function
double num = strtod(chr, &endptr);
// Check if conversion was successful by comparing chr
// and endptr
if (chr == endptr) {
// If chr and endptr are equal, conversion was not
// successful and print an error message
printf("Failed to convert to double\n");
}
else {
// If chr and endptr are not equal, conversion was
// successful and print the converted double value
printf("The converted double is: %f\n", num);
}
return 0;
}
OutputThe converted double is: 3.140000
3. Using sscanf() function
The function sscanf() is a standard library function that resembles scanf(), but it takes a string buffer as its input source.
Syntax:
int sscanf(const char *str, const char *format, ...);
This function takes two arguments:
str: This is a pointer to the string to be read.
Format: This is a string specifying the format of the input to be read.
Example:
C
#include <stdio.h> // header file for input and output functions
int main()
{
// declare a character array and initialize it with a
// string
char chr[] = "3.14";
// declare a variable to hold the converted double value
double num;
// use sscanf() to convert the string in chr to a double
// value
sscanf(chr, "%lf", &num);
printf("%lf", num);
return 0;
}
Above are the methods to convert a char array to Double using built-in functions in C. We can choose any of the above methods.
Similar Reads
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read