This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: scanf issue (store only specified tokens)


----- Original Message ----- 
From: "Carlo Florendo" 


> Hello,
> 
> 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:

e.g.
One has to use:
sscanf(test_string, "%*s%s",  something_stored_here);
instead of 
sscanf(test_string, "%*s%s",  <something_else>, something_stored_here);

In any case, thanks for all those that responded.

Best Regards,

Carlo
------
Carlo Florendo
Astra Philippines Inc.
URL: http://www.hq.astra.ph



  







Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]