Reputation: 73
I have been reading the first chapter of K&R, but I am having trouble with one of the very first problems.
#include <stdio.h>
/* count digits, white space, others */
main(){
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if(c >= '0' && c <= '9')
++ndigit[c-'0'];
else if(c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);
}
I have zero output in the terminal from this. I have tried many different variations of this, but can not seem to get it to output and numbers.
Any help is very appreciated!
Upvotes: 0
Views: 406
Reputation: 9416
BTW, in the years since K&R came out, we have learned a lot about what makes code more reliable/maintainable. Some examples:
#include <stdio.h>
/* count digits, white space, others */
int main ( void ) { /* type explicitly */
int c; /* declare 1 variable per line */
int i;
int nwhite = 0; /* initialize variables when possible */
int nother = 0;
int ndigit[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
while ((c = getchar()) != EOF) { /* use brackets */
if ((c >= '0') && (c <= '9')) { /* explicit precedence is clearer */
++ndigit[c-'0'];
} else if ((c == ' ') || (c == '\n') || (c == '\t')) {
++nwhite;
} else {
++nother;
}
}
printf("digits =");
for (i = 0; i < 10; ++i) printf(" %d", ndigit[i]); /* 1 liner is ok w/{} */
printf(", white space = %d, other = %d\n", nwhite, nother);
return 0; /* don't forget a return value */
}
Upvotes: 0
Reputation: 14792
The problem is, that you do not normally input EOF
from the console. As stated in Tony Ruths answer, it works by redirecting a file to stdin
of the program, because files are terminated by EOF
. Since the entire file is then passed into stdin
, which is read by the program via getch()
, the "end of the input" gets recognized the correct way.
You just don't get to input EOF
via the console, thus not getting any output. (actually there might be some special shortcut for EOF
)
Upvotes: 0
Reputation: 1408
This program requires an input file to be passed to it, but it works as is.
gcc test.c -o test
echo "12345" > data
./test < data
digits = 0 1 1 1 1 1 0 0 0 0, white space = 1, other = 0
Here is another output:
echo "111 111 222" > data
./test < data
digits = 0 6 3 0 0 0 0 0 0 0, white space = 3, other = 0
Upvotes: 2