Talvolta abbiamo la necessità di convertire una stringa numerica (es: “345”) in una variabile numerica. Per fare questo possiamo utilizzare la libreria string.h
.
Qui elencate le principali funzioni per questo scopo:
atoi
atol
atof
strtol
strtoul
strtod
int
).Esempio:
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[] = "123";
int n = atoi(s);
printf("Numero: %d\n", n); // → 123
return 0;
}
atoi
, ma restituisce un long int
.Esempio:
char s[] = "987654321";
long n = atol(s);
// n = 987654321
double
).atoi
, non gestisce errori.char s[] = "3.14";
double x = atof(s);
// x = 3.14
long int
.endptr
→ se non è NULL
, memorizza l’indirizzo del primo carattere non convertito.#include <stdio.h>
#include <stdlib.h>
int main() {
char s[] = "123abc";
char *rest;
long n = strtol(s, &rest, 10);
printf("Numero: %ld\n", n); // → 123
printf("Resto: %s\n", rest); // → "abc"
return 0;
}
unsigned long
).Esempio:
char s[] = "4294967295";
unsigned long n = strtoul(s, NULL, 10);
// n = 4294967295 (max per 32 bit)
#include <stdio.h>
#include <stdlib.h>
int main() {
char s[] = "3.14pi";
char *rest;
double x = strtod(s, &rest);
printf("Numero: %f\n", x); // → 3.140000
printf("Resto: %s\n", rest); // → "pi"
return 0;
}
Funzione | Tipo restituito | Sicurezza | Note |
---|---|---|---|
atoi | int | ❌ | Non gestisce errori |
atol | long int | ❌ | Non gestisce errori |
atof | double | ❌ | Non gestisce errori |
strtol | long int | ✅ | Gestisce basi diverse + errori |
strtoul | unsigned long | ✅ | Come strtol , ma senza segno |
strtod | double | ✅ | Gestisce virgola + notazione scientifica |