Skip to content
Tutorials Center
My learning

Topics

Lesson 44 of 135 ยท Arrays and Strings

Converting Strings and Numbers

Convert strings to numbers in C the safe way with strtol and strtod, detect bad input and overflow, and turn numbers into text with snprintf and sscanf.

Almost every number a C program works with arrives as text first. Command-line arguments, lines typed by a user, configuration files, CSV exports and network messages are all just characters. Before you can add "42" to something, you have to turn the characters '4' and '2' into the integer 42. And when you want to show a result, write it to a file or build a message, you go the other way: from a number back to characters.

C gives you several tools for both directions, and they are not equally good. Some of them (atoi, atof) are simple but silently accept garbage. Others (strtol, strtod) report exactly where parsing stopped and whether the value fit. This lesson shows you how each one behaves, why the strto* family is the right default, and how to wrap it in a small function you can reuse in every program. You'll finish with snprintf and sscanf for formatting and for parsing structured text.

You should already be comfortable with strings and the string functions in <string.h>.

Why atoi is not enough

The quickest way to parse an integer is atoi ("ASCII to integer") from <stdlib.h>. It skips leading whitespace, reads an optional sign and digits, and stops at the first character that isn't a digit. That sounds fine until you feed it something unexpected:

C What atoi does with bad input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The output shows the problem:

  • "42abc" becomes 42. The trailing junk is ignored without a word.
  • "abc" and "" both become 0, which is exactly what "0" gives you. You can't tell "the user typed zero" from "the user typed nothing useful".
  • "3.99" becomes 3, because the . simply ends the number.

There is a worse problem you can't see here: if the text holds a number too big for an int, such as "99999999999", the behavior of atoi is undefined. The standard doesn't promise 0, the maximum, or anything at all. So atoi, atol, atoll and atof are only acceptable when the text is guaranteed to be valid, for example a string your own program produced a moment ago. For anything that comes from outside, use the strto* functions.

strtol: parsing integers with error checks

strtol ("string to long") has this signature:

C
long strtol(const char *restrict text, char **restrict end, int base);

It parses like atoi, but gives you three extra pieces of information:

  1. Where it stopped. If you pass the address of a char * as end, strtol stores a pointer to the first character it did not use. If that's the same as text, no digits were found at all. If it points at anything other than the terminating '\0', there was trailing junk.
  2. Whether the value fit. If the number is outside the range of long, strtol returns LONG_MAX or LONG_MIN and sets errno to ERANGE. Because strtol never sets errno to zero itself, you must set errno = 0 before the call.
  3. Which base to use. The third argument is the base, from 2 to 36, or 0 for "detect it from the prefix".

Passing &end to a function that changes your pointer is a pattern you'll study in Pointers to Pointers. For now, just read it as "tell me where you stopped".

Checking all of that every time is tedious, so wrap it in a function once. This one accepts optional surrounding whitespace, rejects empty input, trailing junk and overflow, and also makes sure the result fits in an int:

C A safe parse_int function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Now every bad string is rejected, "0" is still accepted, and " -17 " shows that surrounding whitespace is fine, so a newline left over from fgets is harmless too. Notice two levels of range checking: "99999999999999999999" overflows long itself (errno == ERANGE), while "2147483648" fits in a 64-bit long but not in a 32-bit int, so the explicit comparison catches it.

Note: isspace and the other <ctype.h> functions need a value that fits in unsigned char (or EOF). Plain char may be signed, so a byte like 'รฉ' in UTF-8 could be negative. The cast (unsigned char)*end avoids undefined behavior. Characters and ASCII explains why.

The whole family works the same way:

Function Result type Overflow returns
strtol long LONG_MIN / LONG_MAX
strtoll long long LLONG_MIN / LLONG_MAX
strtoul unsigned long ULONG_MAX
strtoull unsigned long long ULLONG_MAX
strtoimax / strtoumax intmax_t / uintmax_t (in <inttypes.h>) INTMAX_MIN / INTMAX_MAX / UINTMAX_MAX

strtoul accepts a minus sign. strtoul("-1", &end, 10) doesn't fail: it negates the value in unsigned arithmetic and returns ULONG_MAX (18446744073709551615 with a 64-bit long). If negative input is an error for you, check for a '-' yourself, or parse with strtol/strtoll and test value < 0.

Bases and prefixes

The base argument lets you read other number systems. With base 16, an optional 0x or 0X prefix is allowed. With base 0, strtol looks at the prefix: 0x means hexadecimal, a leading 0 means octal, anything else is decimal.

C Parsing in different bases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Passing NULL as end is allowed when you don't care where parsing stopped, but then you also can't detect junk, so only do it in demos like this one. Base 36 uses the digits 0โ€“9 followed by the letters aโ€“z (case-insensitive), so "zz" is 35 ร— 36 + 35 = 1295.

Be careful with base 0 for user input: "010" becomes 8, not 10, because the leading zero means octal. People type leading zeros in dates and ZIP codes all the time. Use base 10 unless you really want C-style prefixes.

C23 adds binary prefixes: with base 0 or 2, strtol should accept "0b1011". That needs a C library new enough to support it (glibc 2.38 or later, for example). The library on our server is older and stops at the b, so don't depend on it in portable code yet.

Reading several numbers from one string

Because end tells you where the last number stopped, you can call strtol again from that spot. That's a simple, safe way to read a list of numbers out of one line:

C Summing numbers in a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With the preset input the program prints Read 5 numbers, total 35. Change the Input box and run it again. Each strtol call skips the spaces before its number by itself, so you don't need to split the line first. (A version that should reject junk like 10 x 20 would check what *end is when the loop stops.)

strtod: parsing floating-point numbers

strtod ("string to double") follows the same rules as strtol, minus the base argument. It understands everything a C floating-point literal can look like, plus a few extras:

C What strtod accepts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A few lines are worth a closer look:

  • ".25cm" parses as 0.25 and leaves "cm" for you, which is handy when a number is followed by a unit.
  • "0x1.8p1" is a hexadecimal float: 1.8 in hex is 1.5, and p1 means "times 2ยน", so the value is 3.
  • "inf" and "nan" (in any letter case) give infinity and not-a-number. If those shouldn't be legal input, reject them with isfinite from <math.h> (see Floating-Point Numbers).
  • "1e999" is too big for a double: strtod returns HUGE_VAL (infinity) and sets ERANGE.
  • "1e-400" is too small to represent, so it underflows to 0 and also sets ERANGE. Whether a tiny result counts as an error is your decision.

Use strtof for float and strtold for long double. A safe parse_double looks just like parse_int: check end == text, check errno, skip trailing whitespace, and require *end == '\0'.

Note: strtod, atof, printf and scanf use the decimal point of the current locale. A C program starts in the "C" locale, where it's always .. If a program calls setlocale(LC_ALL, "") to adopt the user's settings, strtod("3.14", โ€ฆ) may stop at the . in locales such as German, where the decimal separator is a comma. Parse machine-readable data in the "C" locale.

Numbers to strings with snprintf

Going from a number to text is easier: use snprintf, the bounded version of printf that writes into a character array. Every format specifier from Printing Output with printf works.

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

snprintf never writes more than size bytes, including the terminating '\0'. Its return value is the number of characters the full result would need (not counting the '\0'), or a negative number on an encoding error. That lets you detect truncation, and even ask how big a buffer you need by passing a size of 0:

C Formatting with snprintf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first call writes "12345 i" (7 characters plus '\0' fill the 8-byte buffer) and returns 11, the length of "12345 items". The check needed >= size is the standard truncation test. GCC even spots this particular truncation at compile time, because the value and the buffer size are both constants, and shows a -Wformat-truncation warning above the output. That warning is expected here; when values are only known at run time, the return-value check is your safety net. The second part uses the "measure, then format" idiom; in real code you'd usually malloc(length + 1) instead of a variable-length array, which you'll learn in Dynamic Memory.

Avoid sprintf. sprintf(buffer, ...) has no size argument, so it writes as much as the format produces and can overflow the buffer. An int alone can need 11 characters (-2147483648), and a double printed with %f can need over 300. Always use snprintf with sizeof buffer. Safe String Handling covers more traps like this.

C has no standard itoa function. Some compilers provide one, but snprintf is portable and does the same job in any base printf supports (decimal, octal %o, hex %x). For binary text, you write a small loop that extracts bits, as shown in Bitwise Operators.

Parsing structured text with sscanf

sscanf is scanf reading from a string instead of standard input. It's convenient when text has a fixed shape, such as a date, a time or key=value. Its return value is the number of items it successfully converted, so always compare it with how many you expected.

C sscanf for fixed formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Some details:

  • "17/10/2026" reads 17 as the year, then fails on / because the format expects -, so only 1 field converted. "2026-10" runs out of text after 2 fields.
  • %15[^=] reads up to 15 characters that aren't =. The width keeps the 16-byte key array safe; a bare %s or %[...] without a width can overflow, just like gets.
  • %n doesn't consume anything; it stores how many characters were read so far, so you can find the rest of the string. It doesn't count toward the return value.

sscanf has two weaknesses. First, %d has undefined behavior when the number doesn't fit in an int, so it can't reject overflow the way strtol can. Second, %d happily accepts "12abc" as 12 unless you check what follows. Use sscanf for quick, well-shaped text you mostly trust, and strtol/strtod when every input must be validated. The recommended input pattern from Reading Input with scanf and fgets combines both: read a whole line with fgets, then parse it.

Conversion programs: digits, bases and your own itoa

These are the conversions that exercises and interviews ask for. Most of them are two lines with the tools above, and the rest show what those tools do inside.

  • int to char and back. A digit character and its value differ by '0': '7' - '0' is 7 and '0' + 7 is '7'. For hexadecimal letters use 'a' - 10.
  • long, double and float to text all use snprintf with the right length modifier: %ld, %lld, %.2f. A float is promoted to double in a variadic call, so %f serves both.
  • Binary, octal and hexadecimal to a number is strtol(text, &end, base) with base 2, 8 or 16. Going the other way, %o and %x print octal and hex, while binary has no standard format and needs a loop.
  • itoa is not standard C. Some compilers ship it, but you can write a portable version in a few lines, for any base from 2 to 36.
C Own itoa, bases and digit characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The function fills the buffer from the end, so digits come out in the right order without reversing, and returns a pointer to the first digit inside the buffer (not the buffer start). Negating a long long directly is undefined for the most negative value, so the magnitude is computed in an unsigned type, where wrap-around is well-defined. The NULL returns report a buffer that is too small, so the caller never reads garbage.

Choosing the right tool

Task Use Avoid
Text to integer, from users or files strtol / strtoll with end and errno checks atoi, scanf("%d") without checks
Text to floating-point strtod / strtof with the same checks atof
Text with a fixed shape (dates, key=value) sscanf, checking its return value, widths on %s/%[ unbounded %s
Number to text snprintf with sizeof buffer sprintf, non-standard itoa

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does atoi("12abc") return?

    atoi reads leading digits and stops at the first non-digit without reporting anything. That silent acceptance is why strtol with an end pointer is preferred.
  2. 2. After long v = strtol(text, &end, 10);, which condition means the string contained no number at all?

    If no digits were found, strtol stores the original pointer in end. A result of 0 is ambiguous, because the text may really have been "0".
  3. 3. Why must you write errno = 0; before calling strtol?

    Library functions set errno when something goes wrong but never reset it on success. Clearing it first makes the ERANGE test meaningful.
  4. 4. What does snprintf(buf, 8, "%d items", 12345) return?

    snprintf returns the length the complete output needs, not counting the null terminator. A return value greater than or equal to the buffer size means the output was truncated.
  5. 5. With base 0, what does strtol("010", NULL, 0) return?

    With base 0, a leading 0 selects octal, and 10 in octal is 8. Use base 10 for user input so leading zeros don't change the meaning.

Summary

  • atoi, atol and atof can't report errors: junk becomes 0 or is ignored, and overflow is undefined behavior. Use them only on text you know is valid.
  • strtol, strtoll, strtoul and strtod report where parsing stopped (end) and whether the value fit (errno == ERANGE). Set errno = 0 first, and check end == text and *end.
  • Wrap the checks in a reusable function such as parse_int(text, &out) that returns true or false.
  • The base argument reads hex, octal, binary and up to base 36; base 0 detects 0x and a leading 0 (octal), so prefer base 10 for user input.
  • strtoul silently accepts negative numbers, and strtod accepts inf, nan and hex floats.
  • Convert numbers to text with snprintf; its return value detects truncation and can measure the needed size. Never use sprintf.
  • sscanf parses fixed-shape text; check its return value, give every %s/%[ a width, and remember %d can't detect overflow.

Next: Pointers