Brian O'Brien said:
I am trying to extract a item description and price from a line of text.
A Cup of Coffee $1.23
n = sscanf(str, "%s%*[\t $]%f", item, &price);
But how can I make "A Cup of Coffee" as a single string? How does sscanf know that I
don't want just the "A" of the sentence?
You're dangerously close to needing to write your own parser or
using regexes, but I think this is do-able, as long as your
input format doesn't vary too much.
char item[80];
/* alphanum & blanks only */
n = sscanf(str, "%79[\t 0-9A-Za-z]$%f", item, &price);
OR
/* Anything but '$' */
n = sscanf(str, "%79[^$]$%f", item, &price);
You'll need to strip the trailing blanks from item. I don't think
there's a way to avoid that (unless you can guarantee that the separator
is a tab and there are no tabs in the item description).
Note the use of the field width. It's really not optional. This is a
security hole if you accept input from any untrusted source, and it's a
potential bug even if you do (someday, someone will edit that database
and not know about the length limitation.)
One final note: the use of float (or even double) to store monetary
amounts is looking for trouble. I speak from experience here.