Tsallaka zuwa abun ciki
Justice Tech School

Converting Strings

atoi, strtol and strtod parse numbers. snprintf builds strings safely.

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

int main(void) {
  int n = atoi("42");
  double d = strtod("3.5", NULL);
  char buf[32];
  snprintf(buf, sizeof buf, "n=%d", n);
  printf("%d %.1f %s\n", n, d, buf);
  return 0;
}

Result

42 3.5 n=42

Exercise

Safe formatted write.

(buf, size, "%d", n)

Quiz Test

Why snprintf over sprintf?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.