Question

Convert an int to a String in C with snprintf

cstringinteger

Question

How can I convert an int to a string in C?

I am creating a function that formats the data from a structure as text so that I can save it to a file. What is the correct and safe way to convert an integer field into its string representation?

Short Answer

In C, integers are converted to text by formatting them into a character array. You will learn to use snprintf, choose a correctly sized buffer, detect truncation, and format multiple structure fields safely before writing them to a file.

Concept

C does not have a built-in String type like some other languages. A string in C is an array of char values that ends with a null terminator ('\0').

To convert an int into such a string, use a formatted-output function. The recommended function is snprintf:

snprintf(buffer, buffer_size, "%d", number);
  • buffer is where the resulting text is stored.
  • buffer_size is the total number of bytes available in the buffer.
  • %d formats an int as decimal text.
  • number is the integer to convert.

snprintf matters because it knows the buffer limit. It writes at most buffer_size - 1 visible characters, then adds a terminating \0 when buffer_size is greater than zero. This helps prevent writing past the end of an array.

When formatting a whole structure, it is usually clearer to format all fields directly into one output buffer rather than converting each field separately.

Mental Model

Think of an integer as a numeric value stored in a calculator, while a C string is text written on paper.

snprintf is the printer:

  • The integer is the value to print.
  • The format ("%d") says how it should look on paper.
  • The character array is the sheet of paper.
  • The buffer size is the edge of the paper.

A safe printer must not write beyond the paper. snprintf is given the paper size, so it can stop before overflowing it.

Take Quiz

Syntax and Examples

The basic syntax for an int is:

int snprintf(char *buffer, size_t size, const char *format, ...);

Convert an integer to decimal text:

#include <stdio.h>

int main(void) {
    int score = 42;
    char text[12];

    int written = snprintf(text, sizeof text, "%d", score);

    if (written < 0 || written >= (int)sizeof text) {
        fprintf(stderr, "Conversion failed or was truncated.\n");
        return 1;
    }

    printf("The text is: %s\n", text);
    return 0;
}

The output is:

The text is: 42

text has room for 12 characters. That is enough for a typical 32-bit int: up to 10 digits, an optional minus sign, and the final null terminator. However, using snprintf and checking its return value is safer than relying only on a guessed size.

For a general int buffer size, char text[12] is commonly sufficient when int has at most 32 bits. If portability to unusually large int types matters, use a larger buffer or format directly into the final output buffer.

Step by Step Execution

Consider this code:

#include <stdio.h>

int main(void) {
    int temperature = -7;
    char text[12];

    int needed = snprintf(text, sizeof text, "%d", temperature);
    printf("%s\n", text);

    return 0;
}

Step by step:

  1. temperature stores the numeric value -7. It is not text.
  2. text creates an array with space for 12 char values.
  3. snprintf reads %d, so it formats temperature as a signed decimal integer.
  4. It writes '-' and '7' into text.
  5. It adds \0, making text a valid C string: "-7".
  6. needed receives 2, because two visible characters (- and 7) were needed. The null terminator is not included in this count.
  7. printf uses %s to print the completed string.

If the buffer had been too small, snprintf would still report the number of visible characters it wanted to write. A result greater than or equal to the buffer size means the result was truncated.

Real World Use Cases

Integer-to-text formatting is used whenever numeric data must become human-readable text:

  • Log messages: "User 42 signed in".
  • Configuration and command output: displaying a port number or retry count.
  • Text files: saving a record such as "id=17, quantity=4".
  • CSV-like exports: writing rows containing IDs, totals, and timestamps.
  • Network protocols: producing a textual HTTP header such as Content-Length: 128.
  • User interfaces: displaying scores, progress percentages, and error codes.

For binary file formats, do not convert numbers to strings unless the file format specifically requires text. Binary formats typically write numeric bytes directly using a defined representation.

Take Quiz

Real Codebase Usage

In production C code, developers generally format directly into the destination buffer and check for failure or truncation.

Format an entire structure

#include <stdio.h>

struct Product {
    int id;
    int quantity;
    double price;
};

int format_product(char *out, size_t out_size, const struct Product *product) {
    int written = snprintf(
        out,
        out_size,
        "id=%d,quantity=%d,price=%.2f",
        product->id,
        product->quantity,
        product->price
    );

    return written >= 0 && (size_t)written < out_size;
}

The function returns 1 on success and 0 if formatting fails or the output does not fit.

Write formatted text to a file

#include <stdio.h>

struct Record {
    int id;
    int age;
};

int write_record(FILE *file, const struct Record *record) {
    return fprintf(file, "%d,%d\n", record->id, record->age) >= 0;
}

If the only destination is a file, fprintf often avoids the need for an intermediate string buffer. For data that may contain text fields with commas or newlines, use a clearly defined format and escape or quote those fields correctly.

Common Mistakes

Using itoa

char text[12];
itoa(42, text, 10);

itoa exists on some systems, but it is not part of the ISO C standard library. Code using it may fail to compile on another compiler or platform. Prefer snprintf.

Passing an uninitialized pointer

char *text;
snprintf(text, 12, "%d", 42); /* Undefined behavior */

text points nowhere valid. Allocate storage first:

char text[12];
snprintf(text, sizeof text, "%d", 42);

Forgetting the null terminator

char text[2];
snprintf(text, sizeof text, "%d", 42);

The text "42" needs three bytes: '4', '2', and \0. This buffer is too small, so the output is truncated. Always reserve space for the terminator.

Using the wrong format specifier

long value = 1000000;
printf("%d\n", value); /* Wrong: %d is for int */

Use a specifier matching the type:

printf("%ld\n", value);

For unsigned int, use %u. For values declared with fixed-width integer types such as int64_t, use the macros from <inttypes.h>, such as PRId64.

Ignoring truncation

char text[4];
snprintf(text, sizeof text, "%d", 12345);

This produces truncated text. Save and check the return value from snprintf before using the result.

Writing raw structs as if they were portable text

fwrite(&record, sizeof record, 1, file);

This writes binary memory bytes, not a readable string. It can also include padding bytes and depend on platform details. Use fprintf or snprintf when your file format should be text.

Comparisons

ApproachBest useSafety and portability
snprintfConvert to a buffer or build a formatted lineStandard C; size-aware; check its return value
sprintfLegacy code onlyStandard C, but no buffer limit; can overflow arrays
fprintfWrite formatted text directly to a FILE *Standard C; avoids a temporary buffer
itoaPlatform-specific codeNot ISO-standard C; avoid for portable programs
fwriteDefined binary file formatsWrites bytes, not readable decimal text

snprintf versus sprintf:

char text[12];
snprintf(text, sizeof text, "%d", 42); /* Preferred */

sprintf(text, "%d", 42); /* Unsafe if the value does not fit */

snprintf is usually the correct choice when constructing a string. fprintf is often the simplest choice when immediately writing a formatted record to an already-open file.

Take Quiz

Cheat Sheet

#include <stdio.h>

int value = -123;
char text[12];

int result = snprintf(text, sizeof text, "%d", value);
if (result < 0 || (size_t)result >= sizeof text) {
    /* Formatting failed or text was truncated. */
}
  • A C string ends with \0.
  • %d formats an int.
  • %u formats an unsigned int.
  • %ld formats a long; %lld formats a long long.
  • snprintf returns the number of visible characters it wanted to write, excluding \0.
  • result < 0 means an encoding/formatting error.
  • result >= buffer_size means the output was truncated.
  • Use sizeof array only when the buffer is an actual array in the current scope.
  • Prefer snprintf over sprintf.
  • Prefer fprintf(file, ...) when no intermediate string is needed.

FAQ

How do I convert an int to a string in C?

Use snprintf with %d:

char text[12];
snprintf(text, sizeof text, "%d", number);

Does C have an int to string function?

ISO C does not provide a dedicated standard int-to-string function. Formatted output functions such as snprintf are the standard solution.

Why should I use snprintf instead of sprintf?

sprintf does not know the destination buffer size and can overflow it. snprintf receives a size limit, making it much safer when used with a correct return-value check.

How large should an integer string buffer be?

For many systems, 12 bytes is enough for a 32-bit signed int, including a minus sign and \0. For portable code, use a sufficiently large destination buffer and always detect truncation with snprintf.

Can I write the integer directly to a file without converting it first?

Yes. For a text file, use fprintf(file, "%d\n", value). Use snprintf only when you need the formatted text stored in a buffer first.

Is itoa safe to use in C?

It may work on your current compiler, but it is not a standard C function. Use snprintf for portable C programs.

Does snprintf include the null terminator in its return value?

No. Its return value is the number of visible characters that would be written. The terminating \0 is not counted.

Take Quiz

Mini Project

Description

Create a small text-record formatter for inventory data. The program turns a struct Item into one line of text and writes that line to a file. This demonstrates formatting multiple values, checking for truncation, and handling file errors.

Goal

Save one inventory item as a readable, comma-separated line in inventory.txt.

Requirements

Create a structure with an integer ID, a name, and an integer quantity. Format the structure as id,name,quantity followed by a newline. Use snprintf to build the line safely. Check whether the output buffer was large enough. Write the completed line to a text file and check for file errors.

Take Quiz

Keep learning

Related questions

View more