| | |
Read an Integer from the User, Part 1
Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than
The function
Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in Read an Integer from the User, Part 2. Reading a Floating-Point Value from the User can be done similarly.
scanf("%d", &n), but not bulletproof. It is meant to be a simple but relatively safe demonstration.The function
mygeti reads user input from the stdin into a string using fgets. Then it attempts to convert this string to an integer using sscanf. If both functions succeed, a 1 is returned; if either fails, a 0 is returned.Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in Read an Integer from the User, Part 2. Reading a Floating-Point Value from the User can be done similarly.
#include <stdio.h> int mygeti(int *result) { char buff [ 13 ]; /* signed 32-bit value, extra room for '\n' and '\0' */ return fgets(buff, sizeof buff, stdin) && sscanf(buff, "%d", result) == 1; } 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: 42 value = 42 Enter an integer: 24f value = 24 Enter an integer: 125 help value = 125 */
Similar Threads
- Read an integer in base 4 in C, need help plzzzz (C)
- 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)
| Thread Tools | Search this Thread |
Tag cloud for C
adobe ansi api array arrays asterisks binarysearch calculate centimeter char convert copyanyfile copyimagefile copypdffile cprogramme createcopyoffile csyntax directory drawing dynamic executable fflush file fork frequency getlasterror givemetehcodez graphics gtkgcurlcompiling hacking hardware highest homework i/o inches incrementoperators infiniteloop initialization interest km lazy linked linkedlist linux linuxsegmentationfault list locate logical_drives match matrix microsoft motherboard multi mysql number open opendocumentformat opensource owf pattern pdf performance pointer pointers posix power problem probleminc program programming pyramidusingturboccodes read recursion recv repetition scanf scheduling scripting segmentationfault send shape socketprograming spoonfeeding stack standard string strings structures student suggestions systemcall test testautomation unix user variable voidmain() wab win32api windows.h



