简体   繁体   中英

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').

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 ).

If always there is a space before the number and always the words are two like "step 123".

then below is the code that works.

int main ()
{
  char str[] ="tring 7532";
  char *pch1,*pch2;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch1 = strtok (str," ");
  pch2= strtok (NULL, " ");
  int a=strtol(pch2,(char **)NULL,10);

  printf ("the number is: %d\n",a);

return 0;
}

264> ./a.out
Splitting string "tring 7532" into tokens:
the number is: 7532

You don't define well what you mean part of a string? Is it always the 6th character -of index 5?

You could use strtol , atoi , or perhaps sscanf

Because you just convert the first digit.

if it's always a 3-digit number:

int i = 100 * int(input[5] - '0') + 10 * int(input[5] - '0') + int(input[5] - '0')

you have to move from start to end and check if it comes under digit ascii then convert it into digit

    int digit = 0; i = 0;
    while(input[i] != '\0'){
     if(input[i] >= 48 && input[i] <= 57){

       int temp = input[i] - '0';
       digit  = digit*10 + temp;

     }
    i++;
    }
printf("%i", digit);

You can technically use one of proposed methods, but it might happen that you will need some kind of parser, if you want really robust handling.

You should check if you have keyword "step", then space, and then number in valid format for your input.

For example: what if user enters just "s 1" instead of "step 1". Do you want to start reading after end of input? Or if he enters "step[space][space]-2342344234234234233333" and so on.

char *p;
int i;
p = strchr(input, ' ');
i = atoi(p);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM