hey mates.
i want to get two variables from a string that changes occasionally.
But this code never returns the id. How can i do that?Code:if (sscanf(s, "%s_%s", name, id) >= 1)
(the string is like "#guyab_1" "#aden_25" and so on...)
hey mates.
i want to get two variables from a string that changes occasionally.
But this code never returns the id. How can i do that?Code:if (sscanf(s, "%s_%s", name, id) >= 1)
(the string is like "#guyab_1" "#aden_25" and so on...)
Because the first %s will include _
Try something like this:
Code:sscanf(s, "%[^_]_%s", name, id)
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
scanf, fscanf, sscanf ... all of these return the number of arguments successfully parsed.
since you get the first argument but not the second, the return value is 1 and not 2
Thank you guys. Much appreciated.
Sorry mates but i am in a dilemma now. So didn't want to create a new thread. Here i go:
What about space char? I mean
sscanf(s, "%s %s", name, company) parses a string like 'john nashville' but it also parses 'john nashville ' and so on.. How i can make this to parse only the first string?
As written, name will be "john" and company will be "nashville" and whatever else remains in buffer s will still be there.
The separator for %s is whitespace (of all kinds)
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
To sum it up you're saying it's not possible with sscanf? Right?
I've no idea - you've not exactly posted a consistent set of strings to parse.
If your input is "john nashville IBM", and you're hoping to get "john nashville" into name, and "IBM" into company, then the answer is no.
But if you've got something else going on, you need to post some examples.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
input: 'john IBM has some secrets'
get: 'john IBM'
This is ok.
But i don't want to sscanf parse when the string goes like:
input: 'john IBM has some secrets'
sscanf still does the parsing. I just want to parse a string which is like the first one ''john IBM has some secrets'
%n will tell you how many characters were read, which you can then compare to strlen to see if there were things left over.
Oh thank you again.