Reading a number from stdin

P

pandit

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
 
B

Barry Schwarz

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)))

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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top