C documentation V1 Help

Converting Strings

In C programming, converting strings often involves changing the representation of data, such as converting a string to an integer or vice versa. Let's explore common string conversion operations in C.

1. String to Integer Conversion

Converting a string to an integer can be achieved using the atoi (ASCII to Integer) function from the <stdlib.h> library.

#include <stdio.h> #include <stdlib.h> int main() { const char *numberString = "123"; // Convert string to integer int convertedNumber = atoi(numberString); printf("Converted Number: %d\n", convertedNumber); return 0; }

This program converts the string "123" to an integer using atoi and prints the result.

2. Integer to String Conversion

Converting an integer to a string can be done using the sprintf (String Print Formatted) function.

#include <stdio.h> int main() { int number = 456; char resultString[10]; // Sufficient size to hold the string representation // Convert integer to string sprintf(resultString, "%d", number); printf("Converted String: %s\n", resultString); return 0; }

This program converts the integer 456 to a string using sprintf and prints the result.

3. String to Double Conversion

Converting a string to a double can be done using the atof (ASCII to Float) function from the <stdlib.h> library.

#include <stdio.h> #include <stdlib.h> int main() { const char *doubleString = "123.45"; // Convert string to double double convertedDouble = atof(doubleString); printf("Converted Double: %lf\n", convertedDouble); return 0; }

This program converts the string "123.45" to a double using atof and prints the result.

4. Double to String Conversion

Converting a double to a string can be done using the sprintf function as well.

#include <stdio.h> int main() { double pi = 3.14159; char resultString[20]; // Sufficient size to hold the string representation // Convert double to string sprintf(resultString, "%.2lf", pi); printf("Converted String: %s\n", resultString); return 0; }

This program converts the double 3.14159 to a string with two decimal places using sprintf and prints the result.

Understanding these conversion techniques is crucial for handling various types of data in C programming.

If you have specific questions or if there are additional topics you'd like to explore, feel free to ask!

Last modified: 25 February 2024