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);
bufferis where the resulting text is stored.buffer_sizeis the total number of bytes available in the buffer.%dformats anintas decimal text.numberis 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.
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:
temperaturestores the numeric value-7. It is not text.textcreates an array with space for 12charvalues.snprintfreads%d, so it formatstemperatureas a signed decimal integer.- It writes
'-'and'7'intotext. - It adds
\0, makingtexta valid C string:"-7". neededreceives2, because two visible characters (-and7) were needed. The null terminator is not included in this count.printfuses%sto 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.
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
| Approach | Best use | Safety and portability |
|---|---|---|
snprintf | Convert to a buffer or build a formatted line | Standard C; size-aware; check its return value |
sprintf | Legacy code only | Standard C, but no buffer limit; can overflow arrays |
fprintf | Write formatted text directly to a FILE * | Standard C; avoids a temporary buffer |
itoa | Platform-specific code | Not ISO-standard C; avoid for portable programs |
fwrite | Defined binary file formats | Writes 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.
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. %dformats anint.%uformats anunsigned int.%ldformats along;%lldformats along long.snprintfreturns the number of visible characters it wanted to write, excluding\0.result < 0means an encoding/formatting error.result >= buffer_sizemeans the output was truncated.- Use
sizeof arrayonly when the buffer is an actual array in the current scope. - Prefer
snprintfoversprintf. - 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.
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.
Keep learning
Related questions
2D Array Loop Order and Cache Performance in C
Learn why swapping nested loops changes 2D array performance in C, using row-major memory layout, cache locality, and practical benchmarks.
Array-to-Pointer Conversion in C and C++ Explained
Learn what array-to-pointer conversion means in C and C++, how array decay works, and how it differs from a pointer to an array.
Building More Fault-Tolerant Embedded C++ Applications for Radiation-Prone ARM Systems
Learn practical C++ and compile-time techniques to reduce soft-error damage in embedded ARM systems exposed to radiation.