Ad space (banner)
๐Ÿ”งC Lessons
Lesson 31 / 68

Type Conversion (Casting) Basics

This lesson covers basic type conversion (casting) in C, so you can convert between strings and numbers. It's for anyone searching "C atoi sprintf usage."

Type conversion (casting) โ€” string to number, number to string, and so on โ€” is a basic operation in programming. Use functions like atoi() and sprintf().

The example converts the string "123" to an integer with atoi("123") for use in a calculation, and converts the number 45 to a string with sprintf(buf, "%d", n), writing it into a buffer. Notice the two conversion functions used for each direction.

A common early mistake is not knowing atoi() just returns 0 on failure, without signaling an error. Passing a non-numeric string doesn't raise an error, so strtol() is recommended for safer conversion.

In real projects, type conversion comes up constantly โ€” using a string a user typed as a number in a calculation, or converting a calculation's result into a string for display.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)