| | |
Read an Integer from the User, Part 2
Some issues, such as leading whitespace and trailing characters that cannot be part of a number, were not handled in Read an Integer from the User, Part 1. Here such issues receive lip service.
#include <stdio.h> #include <ctype.h> int mygeti(int *result) { char c, buff [ 13 ]; /* signed 32-bit value, extra room for '\n' and '\0' */ return fgets(buff, sizeof buff, stdin) && !isspace(*buff) && sscanf(buff, "%d%c", result, &c) == 2 && (c == '\n' || c == '\0'); } int main(void) { int value; do { fputs("Enter an integer: ", stdout); fflush(stdout); } while ( !mygeti(&value) ); printf("value = %d\n", value); return 0; } /* my output Enter an integer: one Enter an integer: Enter an integer: f123 Enter an integer: 123f Enter an integer: 123 Enter an integer: 123 Enter an integer: 1.23 Enter an integer: -42 value = -42 */ /* note: this line in the above has a space character following the 123 Enter an integer: 123 */
Similar Threads
- How to read integer from file in c++? (C++)
- how to read integer value in c#? (C#)
- securely read an integer (C)
- Comparing Python and C, Part 1, Integer Variables (Python)
- Code Snippet: Read an Integer from the User, Part 1 (C)
| Thread Tools | Search this Thread |
#include adobe ansi api array asterisks binarysearch changingto char character cm copyimagefile cprogramme creafecopyofanytypeoffileinc createcopyoffile csyntax database directory dynamic execv feet fgets file fork forloop frequency function getlasterror givemetehcodez global grade graphics gtkgcurlcompiling hacking hardware highest histogram i/o include incrementoperators infiniteloop input interest kernel keyboard kilometer license linked linkedlist linux linuxsegmentationfault list locate logical_drives looping loopinsideloop. lowest match matrix meter microsoft motherboard mqqueue mysql number odf opensource owf pattern pdf performance pointer posix probleminc process program programming radix recursion recv repetition research reversing scanf segmentationfault sequential shape socket socketprograming standard string systemcall threads turboc unix user voidmain() wab windows.h windowsapi



