So i was snooping around and trying to find out what sscanf does, so okay its a better scanf
int a = sscanf(buffer, "%d", &n);
if (a != 1)
{
// user didn't input an integer in n ;
}
Now can someone please explain what the buffer is for ? And i've seen some sscanf's that are transfering stuff from buffer to other variables like sscanf(buffer, "%s %*s %d", &bla, &bla1, &bla2);
whats %*s.
Oh well thats all my questions ^_^
Thanks in advance for anyone that tries to help me
Do you know what scanf is for? Because sscanf is exactly the same thing except it reads from a string, not STDIN. That's what the buffer is - the string it's reading from.
As far as %*s, that's a way of telling the scanf functions that the number of characters you want to read is specified in a variable. For example:
This tells sscanf that you want to read in an integer and at most 32 characters into mystring.Code:sscanf("%d %32s", &myint, mystring);
EDIT: I screwed up and got two format specifiers mixed up, so I removed this bit.
Last edited by dargueta; 03-19-2010 at 02:39 PM.
sudo rm -rf /
So lets say
char mystring[] = "Mouhammed age 12";
char string[10];
sscanf(mystring, "%9s %d", string, &age);
That will input Mouhammed in the string " string ", and 12 in the age integer ?
No, unfortunately. (I got that confused with the %n specifier. Next time I'll double-check what I post.) In normal convention, the asterisk means "discard this input." Your format string should be like this:
If you want to specify a variable size, you can use the 'a' modifier (note this is a GNU/C99 extension) to dynamically allocate a buffer. Important: you have to pass in a pointer to your char * pointer, not just your char * pointer. Take this as an example:Code:sscanf(mystring, "%9s %*s %d",string,&age);
Make sure you deallocate name or else you're going to leak memory and probably run out.Code:int age; char *name; const char *mystring = "Mouhammad age 12"; sscanf(mystring, "%as %*s %d", &name, &age); // do something here with name free(name);
sudo rm -rf /
I generally don't advise using non-standard extensions: it will bite you in the ass some day.
Ok...that's weird. I know I edited my first post...
sudo rm -rf /
Well i'm sounding like pain in the ass i know but let me get this straight, i want to know what it accualy works, now i know how's its syntax..
Oh, you mean you want to know the inner workings of sscanf?
sudo rm -rf /
Yes please
That's implementation-specific; everyone can pretty much do it their own way as long as they conform to the standards. You should be able to find the GNU implementation online somewhere with Google.
sudo rm -rf /
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks