This is the mail archive of the
mailing list for the GCC project.
Re: scanf issue (store only specified tokens)
- From: "Carlo Florendo" <carlo at hq dot astra dot ph>
- To: <gcc at gcc dot gnu dot org>
- Date: Wed, 13 Aug 2003 12:22:35 +0800
- Subject: Re: scanf issue (store only specified tokens)
- References: <003601c3614f$31406400$200aa8c0@thorin>
----- Original Message -----
From: "Carlo Florendo"
> I'd like to use scanf to to store only specified tokens.
> The man page of scanf says that
> [ * ] Suppresses assignment. The conversion that follows occurs as usual, but no pointer
> is used; the result of the conversion is simply discarded.
> Isn't the syntax for the `char *format' parameter supposed to be %[*][width][modifiers]type?
> This is my sample code:
> const char *test_string = "first second";
> int main()
> char *something_stored_here, *nothing_stored_here;
> something_stored_here = (char*)malloc(sizeof(char)*100);
> sscanf(test_string, "%*s%s", nothing_stored_here, something_stored_here);
> printf("%s", something_stored_here);
> When the compiled code is run, I get a segmentation fault.
> When I change the scanf line to:
> sscanf(test_string, "%*s%s", NULL, something_stored_here);
> I also get a segmentation fault.
> Howerver, if I I substitute NULL for a properly allocated `nothing_stored_here' variable, all works correctly, except that sscanf
> stores what it reads in `nothing_stored_here' even if I specified in `char *format' that it should not store the first string it
> encounters (i.e. "%*s%s").
After some tweaking, I've finally found the answer to my own question: If one wants to ignore some tokens in scanf,
one just has to omit putting the parameters that are supposed to store the scanned tokens:
One has to use:
sscanf(test_string, "%*s%s", something_stored_here);
sscanf(test_string, "%*s%s", <something_else>, something_stored_here);
In any case, thanks for all those that responded.
Astra Philippines Inc.