![]() |
|
[C] Dealing with the wrong data type for input? - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [C] Dealing with the wrong data type for input? (/showthread.php?tid=5669402) |
Dealing with the wrong data type for input? - God - Jul 14, 2017 Hello, So I've just started C and have been following thenewboston's tutorials. PHP Code PHP Code Thanks. * - Masm4ever - Jul 14, 2017 scanf returns an error code: Code if (scanf("%d", &age)) {* - God - Jul 14, 2017 (Jul 14, 2017 06:57 AM)Masm4ever Wrote: scanf returns an error code: Thanks, this fixed the problem. * - 0xDEAD10CC - Jul 14, 2017 (Jul 14, 2017 06:57 AM)Masm4ever Wrote: scanf returns an error code: Btw, this is not truly the best way, and checking the return for any valid error response is worse than checking for the number of successfully parsed items because even if you want to check for EOF, you can check that in other ways using feof for instance. You should be comparing it against the number of format specifiers you have, checking it for boolean non-zero int is not great. Consider: Code if (scanf("%d %d", ...))If 1/2 was parsed properly, this will still evaluate as being incorrectly "TRUE" for the logic of a successful call, because it wasn't successful. For posterity, it should have been IMO: Code if (scanf("%d", &age) == 1) {You did not correctly explain the return value of scanf() so I can see this being a problem once he starts evaluating things like I've shown above. Lastly, this is only the validation portion. If scanf() fails to parse data from the stdin buffer, it won't junk that data. You can't just loop a call to scanf() expecting it to only consider the next user input. * - Masm4ever - Jul 14, 2017 (Jul 14, 2017 04:05 PM)0xDEAD10CC Wrote: Btw, this is not truly the best way, and checking the return for any valid error response is worse than checking for the number of successfully parsed items With one format specifier, the return value can be 1 or 0; which is what my code checks. But I agree of course that the retval is not an "error code", that was sloppy. Apologies to OP. * - 0xDEAD10CC - Jul 14, 2017 The last thing I'd like to mention about "%d" is: Code int main(void)Overflows you'll have to deal with yourself. In that case, scanf() will still return 1. The function was designed to extract only what it can use to construct a valid value using the specified format string. You can type "1234SDF" and to us that looks like an invalid number -- but to scanf() it see's the 1234 in that as a valid number and parses that, leaving the "SDF" in the STDIN stream buffer. |