use `sscanf` the same as `istringstream`?

462 views Asked by At

Using istringstream, we could read items one by one from a string, for example:

istringstream iss("1 2 3 4");
int tmp;
while (iss >> tmp) {
    printf("%d \n", tmp);  // output: 1 2 3 4
}

could we do this using sscanf?

2

There are 2 answers

5
AnT stands with Russia On BEST ANSWER

You can fairly closely simulate it with this

const char *s = "1 2 3 4";
int tmp, cnt;

for (const char *p = s; sscanf(p, "%d%n", &tmp, &cnt) == 1; p += cnt)
  printf("%d\n", tmp);
0
CAB On

If you can break the string into separate tokens using strtok

  char str[] ="1 2 3 4";
  char * pch;
  pch = strtok (str," ");
  while (pch != NULL)
  {
    int tmp;
    sscanf( pch, "%d", &tmp );
    printf( "%d \n", tmp );
    pch = strtok (NULL, " ");
  }

Otherwise, scanf supports a %n conversion that would allow you to count the number of characters consumed so far (i haven't tested this, there may be pitfalls I haven't considered) ;

  char str[] ="1 2 3 4";
  int ofs = 0;
  while ( ofs < strlen(str) )
  {
    int tmp, ofs2;
    sscanf( &str[ofs], "%d %n", &tmp, &ofs2 );
    printf( "%d \n", tmp );
    ofs += ofs2;
  }