1

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);
Community
  • 1
  • 1
A. Sarid
  • 3,916
  • 2
  • 31
  • 56

4 Answers4

2

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
unwind
  • 391,730
  • 64
  • 469
  • 606
1

You can use sscanf():

char *ptr = "7-35";
int i,j;
sscanf(ptr, "%d-%d", &i, &j);
Ajish Kb
  • 460
  • 1
  • 4
  • 11
0
#include <stdio.h>

int main (){
  char sentence []="789-35";

  int start;
  int end;

  sscanf (sentence,"%d %*c %d",&start,&end);
  printf ("start:%d\nend: %d\n",start,end);

return 0;
}

I have tested this snippet. It works fine

Zain Zafar
  • 1,607
  • 4
  • 14
  • 23
0

Whats the opposite of printing? Scanning!

Use sscanf

sscanf(range,"%d %d", &start, &end);
Sashank
  • 107
  • 2
  • 11