ccharconcatenationgetlineatoi

How to join two numbers of type char and make them int type


Essentially I have a line which ends in two numbers. I can read the numbers eg) '4' and '1'. I want to concatenate them into '41' and then read that as an int type of value 41. Converting a single character to int is straight forward but how would this work for two (or more) characters?

I am grabbing the characters using:

int first_digit = ctoi(line[1]);
int second_digit = ctoi(line[2]);

where ctoi is defined as :

int ctoi( int c ) // https://stackoverflow.com/a/2279401/12229659
{
    return c - '0';
}

Solution

  • Easiest way would be to use a function such as sscanf (provided that line is a proper string)

     int num;
     if (sscanf(line, "%d", &num) != 1) {
        // handle conversion error
      }
    

    Although, scanf in general doesn't provide protection from arithmetic overflow, so for a big number it will fail (and you won't be able to track it).

    strtol and friends, will fail (and will let you know) when you exceed the range.

    You could however build your own function, again with no overflow protection:

    #include <ctype.h>
    #include <stdlib.h>
    
    int stringToInt(char *str) {
           int num = 0;
    
           size_t start = (*str == '-') ? 1 : 0; // handle negative numbers
    
           for (size_t i = start; str[i] != '\0'; i++) {
                  if (isdigit((unsigned char)str[i]) == 0) { // we have a non-digit
                         exit(1); // ideally you should set errno to EINVAL and return or terminate
                  }
    
                  num = (num * 10) + (str[i] - '0');
           }
           return (start) ? -num : num;
    }