Search code examples
ccharintfgets

Converting part of a char* into an int


I am trying to convert part of a char* into an int. For example if a user inputs 'step 783'. I want to convert 783 into an int.

char buffer[100];
char* input = fgets(buffer, sizeof buffer, stdin)
int i = input[5] - '0'; //assume location 5 is where the number will start
printf("%i", i);

Right now, this code just prints out the first number ('7').


Solution

  • You can use the ordinary conversion functions, starting at the desired position:

    int i = atoi(input + 5);
    long int j = strtol(input + 5, NULL, 0);
    

    The second one, strtol(), is particularly useful if you want to find out where the number ended (via the second parameter, see manual).