Read an Integer from the User, Part 3

Dave Sinkula 0 Tallied Votes 550 Views Share

This is a strtol version of Read an Integer from the User, Part 2.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int mygeti(int *result)
{
   char *end, buff [ 13 ];
   fgets(buff, sizeof buff, stdin);
   *result = strtol(buff, &end, 10);
   return !isspace(*buff) && end != buff && (*end == '\n' || *end == '\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
*/
anthonytan 0 Newbie Poster

int mygeti(int *result){ char *end, buff [ 13 ]; fgets(buff, sizeof buff, stdin); *result = strtol(buff, &end, 10); return !isspace(*buff) && end != buff && (*end == '\n' || *end == '\0');}

< any idea that i can check the integer range too?

Dave Sinkula 2,398 long time no c Team Colleague

Once you've obtained an integer value, checking the range out to be trivial, right? How about taking a shot at it?

anthonytan 0 Newbie Poster

Yes, i've solved. thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.