Back to C Programming
2026-04-059 min read

string conversions

Learn string conversions step by step with clear examples and exercises.

Why This Matters

Understanding string conversions is crucial in C programming as it allows you to effectively handle text data and user input. String conversions enable you to convert strings between different formats, such as uppercase and lowercase, or integer to string, which are essential skills for creating robust programs. Mastering string conversions also helps in implementing various real-world applications like parsing command-line arguments, reading configuration files, and validating user input.

Prerequisites

Before diving into string conversions, you should have a good understanding of:

  1. C programming basics
  2. Variables and data types
  3. Arrays
  4. Pointers
  5. Standard library functions like printf(), scanf(), strlen(), and others that handle basic input/output operations and control structures.
  6. Familiarity with basic data structures such as linked lists and trees is also beneficial, although not strictly necessary for this lesson.

Core Concept

String Representation in C

In C, strings are represented as arrays of characters terminated by a null character (\0). This null character indicates the end of the string. Here's an example:

char myString[] = "Hello, World!";

In this example, myString is an array of 13 characters (14 if you count the null terminator). The first 12 characters store the string "Hello, World!", and the 13th character stores the null terminator.

String Conversion Functions

C provides several functions in the standard library to convert strings between different formats:

  • strtoul() (string to unsigned long)
  • atoi() (string to integer)
  • atof() (string to floating point)
  • sscanf() (scan formatted string)
  • sprintf() (format and write string)
  • strtol() (string to long)
  • strtod() (string to double)

Each of these functions takes a format string as an argument, which specifies the expected format of the input. This allows you to convert strings in a flexible manner, accommodating various input formats.

String Conversion Examples

Integer to String

int number = 42;
char str[10]; // Allocate space for a string of up to 9 digits and the null terminator
sprintf(str, "%d", number); // Convert integer to string using sprintf()
printf("%s\n", str); // Output the resulting string

String to Integer

char str[] = "42";
int number;
sscanf(str, "%d", &number); // Convert string to integer using sscanf()
printf("%d\n", number); // Output the resulting integer

Converting a String to Uppercase or Lowercase

char str[] = "Hello, World!";
int i;
for (i = 0; str[i] != '\0'; ++i) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] -= 32; // Convert to uppercase
} else if (str[i] >= 'A' && str[i] <= 'Z') {
// No need to convert uppercase letters as they already are in uppercase
}
}
printf("%s\n", str); // Output the resulting uppercase string

Common Mistakes

  1. Forgetting to allocate enough space for the string: If you don't provide enough space for a string, you may end up overwriting adjacent memory, leading to unexpected behavior or segmentation faults.
  1. Not checking the return value of string conversion functions: Some string conversion functions (like sscanf()) return the number of successful conversions. If the input is not in the expected format, these functions may fail silently, causing your program to behave incorrectly.
  1. Neglecting to handle negative numbers: When converting strings to integers, you should consider handling both positive and negative numbers by using sscanf() with a format string that includes an optional minus sign ("%d%*c").
  1. Not properly initializing variables: In some cases, uninitialized variables may contain garbage values that can lead to incorrect results when performing string conversions.
  1. Using atoi() instead of safer alternatives like strtol() or strtoul(): The atoi() function does not check for invalid input and may result in undefined behavior if the input is not a valid integer. It's recommended to use strtol() or strtoul(), which allow you to specify a base for the conversion and provide more robust error handling.
  1. Not considering white spaces: When converting strings to integers, it's essential to account for white spaces in the input string. You can use the isspace() function from the standard library to check if a character is a whitespace.
  1. Handling non-numeric input: It's important to validate user input and ensure that it is numeric before attempting to convert it to an integer or floating point number.

Worked Example

Let's create a simple program that converts an integer to a string and then back to an integer, demonstrating round-trip conversion:

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

int main() {
int number = 42;
char str[10]; // Allocate space for a string of up to 9 digits and the null terminator

// Convert integer to string using sprintf()
sprintf(str, "%d", number);

printf("Integer: %d\n", number);
printf("String: %s\n", str);

// Convert string back to integer using atoi()
number = atoi(str);

printf("Converted Integer: %d\n", number);

return 0;
}

Output:

Integer: 42
String: 42
Converted Integer: 42

Common Mistakes

Subheadings

  1. Handling overflow and underflow: When converting large numbers, you should be aware of the possibility of overflow or underflow. To handle these cases, you can use functions like strtoul() with a base argument to specify the number system (e.g., decimal, hexadecimal, octal) and check the return value for any errors.
  1. Handling leading zeros: When converting strings to integers, it's essential to consider whether leading zeros should be treated as part of the number or ignored. You can use additional logic to handle this case if needed.
  1. Handling floating-point numbers: When working with floating-point numbers, you should be aware that they may lose precision during conversion. To minimize loss of precision, you can use functions like strtod() and ensure that the input string is properly formatted (e.g., includes a decimal point).
  1. Handling invalid input: It's important to validate user input and handle cases where the input is not in the expected format. You can use regular expressions or other techniques to validate input before attempting conversion.

Practice Questions

  1. Write a program that converts a floating-point number to a string and then back to a floating-point number, demonstrating round-trip conversion.
  2. Write a program that reads an integer from the user, converts it to a string using sprintf(), and then appends another string to the end of the converted integer. Finally, print the resulting concatenated string.
  3. Write a program that reads a string from the user, checks if it is a valid positive or negative integer (ignoring leading zeros), converts it to an integer using sscanf(), and then prints the absolute value of the converted integer.
  4. Write a program that reads a string from the user, converts it to uppercase using a loop, and then prints the resulting string.
  5. Write a program that reads a floating-point number from the user, converts it to a string using sprintf(), appends another floating-point number as a string (with a decimal point and appropriate precision), and then prints the concatenated string.
  6. Write a program that validates user input for a positive integer, converts the input to an integer using sscanf(), and then calculates the factorial of the entered integer using recursion or iteration.
  7. Write a program that reads a date from the user in the format "YYYY-MM-DD" (e.g., 2023-04-15), validates the input, converts each part to an integer, and then prints the corresponding day of the week (e.g., Monday).
  8. Write a program that reads a string from the user, checks if it is a valid email address (using regular expressions or other techniques), and then prints whether the entered email address is valid or invalid.

FAQ

  1. Why does my program crash when I try to convert a string to an integer?
  • Make sure you're checking the return value of the conversion function (e.g., sscanf()) and handling any errors appropriately.
  1. How can I convert a string to an uppercase or lowercase format in C?
  • Use the toupper() and tolower() functions from the standard library.
  1. What is the difference between sscanf() and sprintf() in C?
  • sscanf() reads formatted data from a string, while sprintf() writes formatted data to a string. Both functions are useful for converting strings between different formats.
  1. How can I handle leading zeros in my integer conversion function?
  • You can use the %d format specifier with sscanf() to handle leading zeros as part of the number. However, if you want to ignore leading zeros and only consider digits after them, you may need to implement additional logic.
  1. What is the maximum number of digits I can store in a char array for an integer conversion?
  • The maximum number of digits that can be stored in a char array depends on the size of the char data type. On most modern systems, a char is 8 bits, which allows for storing numbers up to 255 (0-9, A-Z, a-z). However, you should allocate enough space to account for the null terminator and any leading zeros in the input number.
  1. How can I handle floating-point numbers with sprintf() and sscanf()?
  • To convert floating-point numbers using sprintf() or sscanf(), you should use format specifiers like %f for floating-point numbers, %.nf for floating-point numbers with n digits after the decimal point, or %e and %E for scientific notation.
  1. What is the difference between strtol() and strtoul() in C?
  • strtol() converts a string to a long integer (signed), while strtoul() converts a string to an unsigned long integer. Both functions take additional arguments to specify the base of the conversion and handle errors appropriately.
  1. What is the difference between atof(), strtod(), and sscanf("%lf") in C?
  • atof() converts a string to a floating-point number using atoi-like logic, which may not be as robust or accurate as other methods. strtod() is a more modern function that converts a string to a double with better error handling and support for scientific notation. sscanf("%lf") reads formatted data from a string and converts it to a floating-point number using the specified format specifier (%lf).
  1. How can I handle invalid input when using sscanf()?
  • To handle invalid input when using sscanf(), you should check the return value of the function and ensure that it matches the expected number of conversions. If the return value is less than the expected number, it indicates that the input was not in the expected format. You can then handle this case appropriately (e.g., by prompting the user to enter valid input).
  1. How can I convert a string to a hexadecimal or octal number using C?
  • To convert a string to a hexadecimal or octal number, you should use strtoul() with an appropriate base argument (e.g., 16 for hexadecimal, 8 for octal). You can also use regular expressions or other techniques to validate the input and ensure that it is in the expected format before attempting conversion.