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
?
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
?
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;
}
You can fairly closely simulate it with this