Reputation: 295
#include<stdio.h>
#include<ctype.h>
int peekchar() {
int c;
c = getchar();
if (c != EOF) {
ungetc(c, stdin);
}
return c;
}
int readNumber(void) {
int c;
int accumulator = 0;
while ((c = peekchar() != EOF) && isdigit(c)) {
c = getchar();
accumulator *= 10;
accumulator += c - '0';
}
return accumulator;
}
int main() {
int result = readNumber();
printf("%d\n", result);
return 0;
}
I am trying to read an integer written in decimal notation from stdin until the first non-digit. But its not giving the correct result:
M1508444:CProg sb054043$ gcc -g3 readNumber.c -o readNumber
M1508444:CProg sb054043$ ./readNumber
123
0
Can someone please help me identify the problem?
Upvotes: 1
Views: 127
Reputation: 234875
The issue is with operator precedence. c = peekchar() != EOF
is grouped as c = (peekchar() != EOF)
, and so c
is either 0
or 1
, which accounts for the result.
Fix with (c = peekchar()) != EOF
.
Or, given that isdigit
is defined to be 0 for EOF
, your loop conditional can be simplified to
while (isdigit(c = peekchar())){
Upvotes: 5
Reputation: 5601
Hi you need to modify your while loop like below:-
while ( (c = peekchar()) != EOF && isdigit(c)) {
c = getchar();
accumulator *= 10;
accumulator += c - '0';
}
First of all you need to read the value and store it in variable c
and that you can achieve by doing (c = peekchar())
. Once the value stored in c
now your while loop
will first check whether it is EOF
if not then only it will check whether it is a digit or not.
Upvotes: 0