Reputation: 1
I am new to C, and to Ubuntu. I wrote a very simple program to count the number of characters using while
and getchar()
. The program is:
#include <stdio.h>
main() {
int i;
int c= 0;
while ( ( i = getchar() ) != EOF ){
c++ ;
}
printf( "%d characters\n" , c) ;
return 0;
}
I saved it and compiled it using gcc c1.c -o c1
. No errors reported. I executed the program using ./c1
. I give the input as daniweb then I press enter, but the count is displayed. What went wrong? Is it infinite loop? How does getchar()
determine EOF
when input is given from keyboard?
Upvotes: 0
Views: 886
Reputation: 147
Pressing enter sends a new line character to your program, not EOF. As others have mention already, use Ctrl+D to send EOF. If you want to stop reading characters on newline, change your while loop to this:
while ( ( i = getchar() ) != '\n' ){
c++ ;
}
Upvotes: 1
Reputation: 2707
On the terminal you can send EOF to an application by pressing Ctrl+D. You can also do something like this:
echo "blablub" | ./yourprogram
To count how many characters are in blablub. In this case EOF is sent automatically.
Upvotes: 1