scanf issue (store only specified tokens)
Carlo Florendo
carlo@hq.astra.ph
Wed Aug 13 04:26:00 GMT 2003
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").
I'm sure something is wrong with my code (and with my understanding on how to use scanf). I haven't found an answer in google nor
an explanation nor an example to use the scanf family of functions together with the asterisk (*).
Google keywords 1: scanf, examples, usage
Google keywords 2: "scanf examples", usage
Google keywords 3: scanf, tutorial
The C standard shows the function description but doesn't list examples. All the man pages I've seen in google also show the
description of scanf but not usage examples.
If this is not the proper forum to ask C/C++ specific issues, please point out the proper mailing lists. Thanks so much.
Best Regards,
Carlo
------
Carlo Florendo
Astra Philippines Inc.
URL: http://www.hq.astra.ph
More information about the Gcc
mailing list