C
Beginner
1 min read
String Formatting and Parsing
Example
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int parse_int(const char *str, int *out)
{
char *end;
errno = 0;
long val = strtol(str, &end, 10);
if (errno != 0 || end == str || *end != '\0') return -1;
*out = (int)val;
return 0;
}
int main(void)
{
/* snprintf: safe formatted string building */
char buf[128];
int n = snprintf(buf, sizeof(buf),
"User: %-10s Age: %3d Score: %.2f",
"Alice", 30, 98.756);
printf("snprintf wrote %d chars: \"%s\"\n", n, buf);
/* sscanf: parsing a structured line */
const char *line = "Bob 25 87.5";
char name[32];
int age;
double score;
int parsed = sscanf(line, "%31s %d %lf", name, &age, &score);
if (parsed == 3)
printf("Parsed: name=%s age=%d score=%.1f\n", name, age, score);
/* strtol: safe string-to-int with error detection */
int value;
const char *inputs[] = { "42", " -17", "3.14", "99abc", "xyz" };
for (int i = 0; i < 5; i++) {
if (parse_int(inputs[i], &value) == 0)
printf("'%s' -> %d\n", inputs[i], value);
else
printf("'%s' -> parse error\n", inputs[i]);
}
return 0;
}