Say If i want an input to be
[Name] [Name]
How would I detect
[Name] [Name] [Name]
and return error?
Here is what I have so far,
char in[20];
char out[20];
scanf(" %s %s", out, in);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This is homework, so you might be required to work under certain (arbitrary) restrictions. However, the phrase “
scanferror handling” is something of an oxymoron in the C programming language.The best way to do this is to read in a line/other suitable chunk and parse it with C string functions. You can do it in one line of
scanfbut there are many drawbacks:"%["format ofscanfisn’t mandated in the standard.scanfalso gives you very little control over how you handle whitespace.EDIT: I initially thought from your question that the names were contained in brackets (a la
"[Bruce] [Wayne]") but it now appears that was merely your convention for denoting a placeholder.Anyway, despite my intense dislike of
scanf, it has its uses. The biggest killer (for me) is the inability to distinguish between line endings and simple space separation. To fix that, you can callfgetsto read the data into a buffer, then callsscanfon the buffer. This gives you both a) safer reading (scanfmesses with the ability of other more straightforward functions to read from a buffer) and b) the benefits ofscanfformats.If you have to use
scanf, your format basically be this:With the third being undesirable. As @Constantinius‘s answer shows, you’d need to read data into three buffers, and check whether or not the third passed. However, if you’re reading multiple consecutive lines of this data, then the first entry of the next line would satisfy the third slot, falsely giving you an error. I highly recommend using
fgetsandsscanfor ditching thesscanffor more precise manual parsing in this case.Here’s a link to the
fgetsman page if you missed the one I snuck in earlier. If you decide to ditchsscanf, here are some other functions to look into:strchr(orstrspn, orstrcspn) to find how long the name is,strcpyormemcpy(but please notstrncpy, it’s not what you think it is) to copy data into the buffers.