A. Sarid A. Sarid - 1 year ago 77
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:


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download