Baljeet
Member
- Jan 31, 2011
- 76
- 0
Read an Integer from the User, Part 1
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than 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
All Credits goes to one who really made this...
Obtaining user input can be done in many surprisingly different ways. This code is somewhere in the middle: safer than 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.
Code:
[COLOR="Green"]#include [B]<[/B]stdio.h[B]>[/B][/COLOR]
[COLOR="Blue"]int [/COLOR][COLOR="Red"]mygeti[/COLOR]([COLOR="Blue"]int [/COLOR]*result)
{
[COLOR="Blue"]char [/COLOR]buff [ [COLOR="Teal"]13 [/COLOR]]; [COLOR="Silver"]/* signed 32-bit value, extra room for '\n' and '\0' */[/COLOR]
[COLOR="Blue"]return [/COLOR][COLOR="Red"]fgets[/COLOR](buff, [COLOR="Blue"]sizeof [/COLOR]buff, [COLOR="DarkOrchid"]stdin[/COLOR]) && [COLOR="Red"]sscanf[/COLOR](buff, [COLOR="Teal"]"%d"[/COLOR], result) == [COLOR="Teal"]1[/COLOR];
}
[COLOR="Blue"]int [/COLOR][COLOR="Red"]main[/COLOR]([COLOR="Blue"]void[/COLOR])
{
[COLOR="Blue"]int [/COLOR]value;
[COLOR="Blue"]do [/COLOR]{
fputs([COLOR="Teal"]"Enter an integer: "[/COLOR], [COLOR="DarkOrchid"]stdout[/COLOR]);
fflush([COLOR="DarkOrchid"]stdout[/COLOR]);
} [COLOR="Blue"]while [/COLOR]( ![COLOR="Red"]mygeti[/COLOR](&value) );
[COLOR="Red"]printf[/COLOR]([COLOR="Teal"]"value = %d\n"[/COLOR], value);
[COLOR="Blue"]return [/COLOR][COLOR="Teal"]0[/COLOR];
}
[COLOR="Silver"]/* 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
*/[/COLOR]
Leading whitespace, and other trailing characters are some things not handled. Those issues are handled in
You must be registered for see links
.
You must be registered for see links
can be done similarly.All Credits goes to one who really made this...