Reputation: 11
I found this book have many people suggest for newbie, but some code on it doesn't work, although I code it exactly like the code in the book but it still don't work
#include <stdio.h>
main()
{
int a ;
for (a = 0; getchar() != EOF ; ++a);
printf ("%d",a);
}
It looks like after the loop it ends immediately, code after the loop is not executed.
Is this book is too old? Is there any another book for self learning c programming?
Upvotes: 0
Views: 115
Reputation: 19864
int main( void )
{
int a ;
for (a = 0; getchar() != EOF ; ++a);
printf ("%d\n",a);
return 0;
}
On Unix platform run this code and when you want to exit introduce EOF
by ctrl+d
, if you are on windows then EOF
is introduced by ctrl+z
So basically when you exit you will get the count of number of times your loop ran.
If you want to print out each input then you need to get rid of the ;
at the end of for
loop
int main( void )
{
int a ;
for (a = 0; getchar() != EOF ; ++a)
printf ("%d\n",a);
return 0;
}
Upvotes: 1
Reputation: 1440
I strongly suspect that the console closes immedeately after the loop ends. Try to insert something like system("pause")
to prevent the console from closing.
The loop loops until you type EOF and prints the number of characters typed so far. To type EOF, you have to hit ctrl-z and return (in a test I had to do this after a return, so return, then ctrl-z, then return). If the console closes directly after the ctrl-z, you can add this system("pause")
to wait for another key afterwards, so you see the output.
Upvotes: 0