Search code examples
c++scanfistringstream

use `sscanf` the same as `istringstream`?


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?


Solution

  • 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);