A. Sarid A. Sarid - 9 months ago 44
C Question

Splitting string into two integers

I have a string

that represents a range, for example:


I am looking for a simple way to split it into two integers
int begin
int end

I already saw this and this, but I am actually searching for some kind of a "one line" command if there exist any.

It is actually the opposite of doing:



The opposite of printing is scanning, and you'd use sscanf():

unsigned int start, end;
if(sscanf(range, "%u-%u", &start, &end) == 2)
  printf("start=%u, end=%u\n", start, end);

Some notes:

  • We use unsigned int and %u to make the embedded dash non-ambigous
  • Always check the return value to make sure the scanning succeeded