A. Sarid A. Sarid - 1 month ago 8
C Question

Splitting string into two integers

I have a string

range
that represents a range, for example:

"7-35"


I am looking for a simple way to split it into two integers
int begin
and
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:

sprintf(range,%d-%d,start,end);

Answer

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
Comments