On 30 Nov 2005 03:03:18 -0800, "Saif" <sa****@gmail.com> wrote:
nick wrote: <snip> so if i want to read the words in the string one by
one, just like scanf, what should i do?
If all you're going to read is words (strings), you can increment the
buffer pointer passed to sscanf by the length of the string previously
read.
Assuming your complete string is pointed to by char *str and you want
to read each word from it into another already allocated character
array char *word. Then...
/*Read first word*/
sscanf(str,"%s", word);
/*Read next word*/
sscanf(str+strlen(word), "%s", word);
You can repeat this to read consecutive strings.
%s _skips whitespace_ and then reads a string of non-whitespace, i.e.
a "word". Or fails due to hitting the end of the input, which you
should catch by checking the return value, as you should for all
*scanf variants. strlen(word) doesn't allow for the whitespace. If
there is leading whitespace in the input string, this will (first)
fail for second word; otherwise for the third.
Also, %s (and %[) in *scanf should always be given with a length
limit, to prevent either accidentally or maliciously exceeding the
actual object (buffer) size and causing Undefined Behavior, which in
the latter (malicious) case is likely to be destroying your data
and/or stealing your money. Unless you are absolutely 100% sure the
input is valid, which in practice is only if was generated by a valid
sprintf call or similar in the line immediately preceding the sscanf
call, in which case you already have the data and don't need to scan.
Try:
char * ptr = str; /* if not already a pointer you can spare */
int used;
if( sscanf (ptr, "%Ns%n", word, &used) < 1 ) /* error */
ptr += used;
if( sscan (ptr, ...
- David.Thompson1 at worldnet.att.net