3-way Convert String to int in C

1. Using atoi()

The atoi() function in C is used to convert a string to an integer. It stands for “ASCII to integer”. It takes a null-terminated string as an argument and returns its value as an integer.

Syntax:

int atoi(const char* str);

Example

#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
    char a[] = "54321"; 
    int val = atoi(a); 
    printf("%d", val); 
    return 0; 
} 

Output

54321

2. Using strtol()

The strtol() function takes a null-terminated string as an argument and returns its value as an integer. It stands for “string to long”.

Syntax:

long int strtol(const char* str, char** endptr, int base);

Example

#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
    char a[] = "54321"; 
    int val = strtol(a, NULL, 10); 
    printf("%d", val); 
    return 0; 
} 

Output

54321

3. Using sscanf()

The sscanf() function takes a string as an argument and reads it according to the given format. It stands for “scan string”.

Syntax:

int sscanf(const char* str, const char* format, …);

Example

#include <stdio.h> 
#include <stdlib.h> 
  
int main() 
{ 
    char a[] = "54321"; 
    int val; 
    sscanf(a, "%d", &val); 
    printf("%d", val); 
    return 0; 
} 

output

54321

Leave a Reply