making sure only integer is input

Discussion in 'C Programming' started by Radith, Nov 19, 2005.

  1. Radith

    Radith Guest

    Hi All,

    I have a number guessing game in which users try to guess a random number.
    Obviously, input is required of type int.
    BUT, when a user inputs a string the program will result in an undesired
    infinite loop.
    Now, I know a string is not what we're after but in terms of error-handling;
    How can we prevent users from entering a string?
    and if we can't do that:
    How can we make sure if a string is entered, it is realized and discarded.
    Implying, that the user is warned about the mistake and prompted again in
    hope of correct input this time??

    I have not included my program here because it is unncessarily large (still
    a begginer), but if y'all want; more than happy to attach it.

    Thanks for all your time in advance.
     
    Radith, Nov 19, 2005
    #1
    1. Advertising

  2. Radith

    Jordan Abel Guest

    On 2005-11-19, Radith <> wrote:
    > Hi All,
    >
    > I have a number guessing game in which users try to guess a random number.
    > Obviously, input is required of type int.
    > BUT, when a user inputs a string the program will result in an undesired
    > infinite loop.


    Don't use scanf in that way.
     
    Jordan Abel, Nov 19, 2005
    #2
    1. Advertising

  3. Radith

    bitshadow Guest

    Jordan Abel wrote:
    > On 2005-11-19, Radith <> wrote:
    > > Hi All,
    > >
    > > I have a number guessing game in which users try to guess a random number.
    > > Obviously, input is required of type int.
    > > BUT, when a user inputs a string the program will result in an undesired
    > > infinite loop.

    >
    > Don't use scanf in that way.


    or still use scanf since he is a biginner and check the return value
    and provide a appropiate prompt before excepting input again. Nothing
    wrong with using scanf as long as you use it correctly.

    while (scanf("%d",&num) !=1)/*while not input looking for*/
    while( (getchar() !='\n') ); /*eat garbege in stdin that scanf
    has*/
    puts("puts please enter an integer");/*prompt for proper input*/
     
    bitshadow, Nov 19, 2005
    #3
  4. Radith

    vire Guest

    Try to deal every input as a string.if it is a num,change it into the
    number.
    or fflush(stdin); after your scanf(...)
    just like:

    int a;
    while(scanf("%d",&a)!=1)fflush(stdin);
     
    vire, Nov 19, 2005
    #4
  5. Radith

    Skarmander Guest

    vire wrote:
    > Try to deal every input as a string.if it is a num,change it into the
    > number.
    > or fflush(stdin); after your scanf(...)
    > just like:
    >
    > int a;
    > while(scanf("%d",&a)!=1)fflush(stdin);
    >


    Do *not* use fflush(stdin). It's not just nonstandard, it's completely
    undefined. See http://www.eskimo.com/~scs/C-faq/q12.26.html. Write code
    that doesn't need such tricks instead.

    S.
     
    Skarmander, Nov 19, 2005
    #5
  6. Radith

    Simon Biber Guest

    Radith wrote:
    > Hi All,
    >
    > I have a number guessing game in which users try to guess a random number.
    > Obviously, input is required of type int.
    > BUT, when a user inputs a string the program will result in an undesired
    > infinite loop.
    > Now, I know a string is not what we're after but in terms of error-handling;
    > How can we prevent users from entering a string?
    > and if we can't do that:
    > How can we make sure if a string is entered, it is realized and discarded.
    > Implying, that the user is warned about the mistake and prompted again in
    > hope of correct input this time??
    >
    > I have not included my program here because it is unncessarily large (still
    > a begginer), but if y'all want; more than happy to attach it.
    >
    > Thanks for all your time in advance.


    Here's a function that demonstrates one safe way to read in an integer,
    and reject invalid input. It reads a line of text and then checks
    whether it consists solely of digits. If so, it is converted to an
    integer and if there was no error, the integer is returned. Otherwise,
    another line is read, and so on.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <errno.h>

    long read_integer(void)
    {
    /* declare a buffer for holding the input line */
    char buf[100] = "";

    /* output the initial prompt */
    printf("Enter an integer: ");
    fflush(stdout);

    /* while the user inputs a line of text */
    while(fgets(buf, sizeof buf, stdin))
    {
    /* Remove the newline character from the buffer */
    char *p = strchr(buf, '\n');
    if(p) *p = 0;

    /* check if input contains only digits */
    if(strspn(buf, "0123456789") == strlen(buf))
    {
    long result;
    errno = 0;

    /* if no conversion error, then break */
    result = strtol(buf, 0, 10);
    if(errno == 0)
    return result;
    }

    /* Otherwise, output another prompt */
    printf("Invalid input, try again: ");
    fflush(stdout);
    }

    if(feof(stdin))
    {
    printf("End of file reached\n");
    return -1;
    }

    printf("Error reading input\n");
    return -2;
    }

    If the number returned by this function is negative, some unrecoverable
    error occurred.

    --
    Simon.
     
    Simon Biber, Nov 19, 2005
    #6
  7. On Sat, 19 Nov 2005 14:52:53 +1300, in comp.lang.c , "Radith"
    <> wrote:

    >Hi All,
    >
    >I have a number guessing game in which users try to guess a random number.
    >Obviously, input is required of type int.
    >BUT, when a user inputs a string the program will result in an undesired
    >infinite loop.


    Yes, if you're using scanf. Don't do that. The FAQ has some hints
    about why not to use scanf.

    Use fgets, parse the string to see if its a number, then handle
    appropriately.
    --
    Mark McIntyre
    CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
    CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

    ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
    http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
    ----= East and West-Coast Server Farms - Total Privacy via Encryption =----
     
    Mark McIntyre, Nov 19, 2005
    #7
  8. Radith

    Rob Adams Guest

    Simon Biber wrote:
    > Radith wrote:
    >
    >> How can we make sure if a string is entered, it is realized and
    >> discarded. Implying, that the user is warned about the mistake and
    >> prompted again in hope of correct input this time??
    >>

    >
    > Here's a function that demonstrates one safe way to read in an integer,
    > and reject invalid input. It reads a line of text and then checks
    > whether it consists solely of digits. If so, it is converted to an
    > integer and if there was no error, the integer is returned. Otherwise,
    > another line is read, and so on.
    >
    > #include <stdio.h>
    > #include <string.h>
    > #include <stdlib.h>
    > #include <errno.h>
    >
    > long read_integer(void)
    > {
    > /* declare a buffer for holding the input line */
    > char buf[100] = "";
    >
    > /* output the initial prompt */
    > printf("Enter an integer: ");
    > fflush(stdout);
    >
    > /* while the user inputs a line of text */
    > while(fgets(buf, sizeof buf, stdin))
    > {
    > /* Remove the newline character from the buffer */
    > char *p = strchr(buf, '\n');
    > if(p) *p = 0;
    >
    > /* check if input contains only digits */
    > if(strspn(buf, "0123456789") == strlen(buf))
    > {
    > long result;
    > errno = 0;
    >
    > /* if no conversion error, then break */
    > result = strtol(buf, 0, 10);
    > if(errno == 0)
    > return result;
    > }
    >
    > /* Otherwise, output another prompt */
    > printf("Invalid input, try again: ");
    > fflush(stdout);
    > }
    >
    > if(feof(stdin))
    > {
    > printf("End of file reached\n");
    > return -1;
    > }
    >
    > printf("Error reading input\n");
    > return -2;
    > }
    >
    > If the number returned by this function is negative, some unrecoverable
    > error occurred.



    Just because I'm feeling mean, I'll point out that the code listed above
    does the wrong thing when presented with the output of either of the
    programs listed below.

    #include <stdio.h>
    int main(void)
    {
    printf("%*s99\n", 99, "");
    return 0;
    }


    #include <stdio.h>
    int main(void)
    {
    printf("\n");
    return 0;
    }


    Rob
     
    Rob Adams, Nov 22, 2005
    #8
  9. Radith

    Simon Biber Guest

    Rob Adams wrote:
    > Simon Biber wrote:
    >
    >> Radith wrote:
    >>
    >>> How can we make sure if a string is entered, it is realized and
    >>> discarded. Implying, that the user is warned about the mistake and
    >>> prompted again in hope of correct input this time??
    >>>

    >>
    >> Here's a function that demonstrates one safe way to read in an
    >> integer, and reject invalid input. It reads a line of text and then
    >> checks whether it consists solely of digits. If so, it is converted to
    >> an integer and if there was no error, the integer is returned.
    >> Otherwise, another line is read, and so on.
    >>

    [snip]
    >>
    >> If the number returned by this function is negative, some
    >> unrecoverable error occurred.

    >
    > Just because I'm feeling mean, I'll point out that the code listed above
    > does the wrong thing when presented with the output of either of the
    > programs listed below.
    >
    > #include <stdio.h>
    > int main(void)
    > {
    > printf("%*s99\n", 99, "");
    > return 0;
    > }
    >
    >
    > #include <stdio.h>
    > int main(void)
    > {
    > printf("\n");
    > return 0;
    > }


    Good catches. I think this solves the problems.

    long read_integer(void)
    {
    /* declare a buffer for holding the input line */
    char buf[100] = "";

    /* output the initial prompt */
    printf("Enter an integer: ");
    fflush(stdout);

    /* while the user inputs a line of text */
    while(fgets(buf, sizeof buf, stdin))
    {
    /* Remove the newline character from the buffer */
    char *p = strchr(buf, '\n');
    if(p)
    {
    *p = 0;
    }
    else /* no newline found */
    {
    int ch;
    /* read and discard the rest of the line */
    while((ch = getchar()) != EOF && ch != '\n');
    if(ch == EOF) break;
    printf("Line too long, try again: ");
    fflush(stdout);
    continue;
    }

    if(buf[0] == 0) /* empty line */
    {
    printf("Empty line not acceptable, try again: ");
    fflush(stdout);
    continue;
    }

    /* check if input contains only digits */
    if(strspn(buf, "0123456789") == strlen(buf))
    {
    long result;
    errno = 0;

    /* if no conversion error, then return */
    result = strtol(buf, 0, 10);
    if(errno == 0)
    return result;
    }

    /* Otherwise, output another prompt */
    printf("Invalid input, try again: ");
    fflush(stdout);
    }

    if(feof(stdin))
    {
    printf("End of file reached\n");
    return -1;
    }

    printf("Error reading input\n");
    return -2;
    }

    --
    Simon.
     
    Simon Biber, Nov 22, 2005
    #9
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Curt_C [MVP]
    Replies:
    5
    Views:
    376
    Karim
    May 19, 2004
  2. Nathan Sokalski
    Replies:
    1
    Views:
    7,192
    CodeMeister
    Jun 17, 2005
  3. Hari Sekhon
    Replies:
    11
    Views:
    584
    Eric S. Johansson
    Oct 3, 2006
  4. Tim Williams
    Replies:
    9
    Views:
    291
    Lawrence D'Oliveiro
    Oct 7, 2006
  5. Replies:
    0
    Views:
    560
Loading...

Share This Page