Convert Char* to Int in C

  1. Use the strtol Function to Convert char* to int in C
  2. Properly Verify strtol Function’s Results to Convert char* to int in C

This article will explain several methods of how to convert char* to int in C.

Use the strtol Function to Convert char* to int in C

The strtol function is part of the C standard library, and it can convert char* data to long integer value as specified by the user. The function takes 3 arguments, the first of which is the pointer where the string is located. Note that this char pointer argument is not modified and has a const qualifier. The second argument can be utilized to store the first invalid character encountered or the whole string in case there were no digits found. The third argument specifies the base of the number to be converted, and the value of this argument should be between 2 and 36. The following example shows how to convert elements from a char* array to integers and output them to the console.

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

void printIntegers(long int arr[], size_t size)
{
    for (size_t i = 0; i < size; i++)
        printf("%4ld | ", arr[i]);
    printf("\n");
}

int main(int argc, char *argv[]) {
    char *arr[] = {"12", "33", "43", "23", "90"};

    size_t len = sizeof arr / sizeof arr[0];
    long int arr3[len];
    for (int i = 0; i < len; ++i) {
        arr3[i] = strtol(arr[i], NULL, 10);
    }
    printIntegers(arr3, len);

    exit(EXIT_SUCCESS);
}

Output:

12 |   33 |   43 |   23 |   90 |

As an alternative, one can take program arguments as the input strings and convert them into integer types. Note that we need to use int argc, char* argv[] as the parameters of the main function to access the program arguments and process them. The next sample code checks if the user-provided at least the single argument to the program and, if not, exits displaying the corresponding error message.

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

void printIntegers(long int arr[], size_t size)
{
    for (size_t i = 0; i < size; i++)
        printf("%4ld | ", arr[i]);
    printf("\n");
}

int main(int argc, char *argv[]) {
    if (argc < 2) {
        printf("Usage: ./%s int1 int2 int3...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    long int arr2[argc-1];
    for (int i = 0; i < argc-1; ++i) {
        arr2[i] = strtol(argv[i+1], NULL, 10);
    }
    printIntegers(arr2, argc - 1);

    exit(EXIT_SUCCESS);
}

Properly Verify strtol Function’s Results to Convert char* to int in C

Even though we successfully used the strtol call to convert strings passed as program arguments to integers in the previous example, there is a great chance the given program would fail. It’s recommended to implement the error checking routines for the strtol function call to guarantee a robust program execution with corresponding error logging. We will check if the converted integer is within the range of type long and if the conversion itself was unsuccessful. Additionally, we will check if there are any characters after the valid integer and if the given input is a decimal number. Mind though, we will print the error messages to stderr stream in each case and not terminate the program, but you should consider another handling routine based on your needs.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <limits.h>

void printIntegers(long int arr[], size_t size)
{
    for (size_t i = 0; i < size; i++)
        printf("%4ld | ", arr[i]);
    printf("\n");
}

int main(int argc, char *argv[]) {

    if (argc < 2) {
        printf("Usage: ./%s int1 int2 int3...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    long int num;
    char *endptr, *str = argv[1];
    errno = 0;
    long ret = strtol(str, &endptr, 10);

    if (str == endptr) {
        fprintf(stderr, "%s: not a decimal number\n", str);
    } else if ('\0' != *endptr) {
        fprintf(stderr, "%s: extra characters at end of input: %s\n", str, endptr);
    } else if ((LONG_MIN == ret || LONG_MAX == ret) && ERANGE == errno) {
        fprintf(stderr, "%s out of range of type long\n", str);
    } else if (errno != 0 && ret == 0) {
        fprintf(stderr, "%s no conversion was performed\n", str);
    } else {
        num = ret;
        printf("num: %ld\n", num);
    }

    exit(EXIT_SUCCESS);
}
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - C Int

  • Convert Integer to Char in C