3

How can I format fscanf to format the input {'name surname', 'username', points} to strings which do not contain apostrophes

fscanf(fp,"{%s %s %d}",name,username,username1);
2

1 Answer 1

5

This should work:

fscanf(fp,"{'%[a-zA-Z ]', '%[a-zA-Z ]', %d}",name,username,username1);
Sign up to request clarification or add additional context in comments.

7 Comments

You could use %[^'] more succinctly, and allow hyphenated names. Mr O'Rourke still suffers, of course, but that's a definitional problem for the questioner. It's also curious that username1 is a pointer to an integer. Often, that would be &username1 — but without the variable definitions, it's hard to know what's correct. It would be good to put upper bounds on the number of characters read into the strings to avoid buffer overflow (%49[^'] for char name[50];). And the return value should be tested to ensure 3 values were read.
@JonathanLeffler - Regarding your comment: "You could use %[^'] more succinctly". Keeping it simple, I have tried "{'%[^'], '%[^'], %d", (matches only 1 parameter, the 1st one), and have also tried "{'%[^'], '%[a-zA-Z], %d". with same result. Can you explain then how exactly would you use %[^'] more succinctly?
@ryyker: You should have looked for the quote before the comma (twice): "{'%[^']', '%[^']', %d".
@ryyker: The negated scan set is a trifle dangerous — it includes newlines, for example, so if the data is malformed, things could go badly awry, especially without lengths to protect from buffer overflow. It would be safer to use %49[^'\n] as the scan set, for example (assuming char name[50];). It would probably be better to use fgets() to read lines and then sscanf() to parse it; that avoids the newline fiasco, and allows a second chance at parsing the line if Mr O'Rourke's name turns up in the data. […continued…]
[…continuation–] You could simply be more inclusive: %49[a-zA-Z -] to scan for letters, blanks, dashes. If you could have Mr. P. J. O'Neil in the data, add . to the list. Note that the dash on its own must be first or last. That then leaves those with accents in their names unreadable (UTF-8 presents extra problems). The negated scan set also allows digits and other punctuation into the name field — that may or may not be a significant problem. GIGO — Garbage In, Garbage Out.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.