Reading a number from stdin

Discussion in 'C Programming' started by pandit, May 21, 2014.

  1. pandit

    pandit Guest

    AIM: To read a number from standard input

    WHAT I DID: I use getchar() to read a single digit. Can use strtol() for numbers more than one digit long.

    PROBLEM: isn't there a better way ?

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


    int main(void)
    {
    int i = 0;

    i = getchar();
    if((EOF == i) && (ferror(stdin)))
    {
    printf("ERROR reading input @LINE = %d\n", __LINE__);
    }
    else
    {
    i = i - '0';
    }

    return 0;
    }


    -- output here --
    ../a.out
    123

    output
    1
     
    pandit, May 21, 2014
    #1
    1. Advertisements

  2. If ferror returns true, the first relational test will always be true
    and logically unnecessary. It may still be desirable in the sense
    that if the test evaluates to false the call to ferror will not occur
    and this may save some processing time. But since we are talking
    about user input the savings will be immeasurably small compared to
    the user's actions.

    This code will not let the user hit Enter to terminate his input.
     
    Barry Schwarz, May 21, 2014
    #2
    1. Advertisements

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.