Reputation: 23
I'm new here , asking questions at least. Always have been able to find good answers here. Trying to get back into programming and relearning C but ran into weird issue.
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld \n", nc);
}
When I run it, after I type in any amount of characters and hit enter, it does not print the value of nc. After hitting enter, I can start typing again and well, same story. Really can't see what could be wrong. The only way it works is if I place both ++nc and the printf within brackets. But then when I hit enter, it gives the value 1-to-nc, which is not what I want. I just want nc. Needless to say the type is not the issue either. Thanks in advance
Upvotes: 1
Views: 1187
Reputation: 1749
try
while(getchar() != '\n') nc++;
Edit : Assuming the input taken from console, '\n' suffices.
Upvotes: 1
Reputation: 837
If you just want to get nc printed inside the loop, you should include the print statement in the loop like so:
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF) {
++nc;
printf("%ld \n", nc);
}
}
That prints nc once for each character after hitting [enter], maybe not what you want.
If you want to print nc once per line use scanf and do:
#include <stdio.h>
#include <string.h>
main()
{
long nc;
nc = 0;
char buf[128];
while (scanf("%s",&buf) > 0) {
int len = strlen(buf);
nc += len;
printf("%ld \n", nc);
}
}
Upvotes: 0
Reputation: 23268
Type Ctrl-D
in your terminal to send EOF
. You may want
while (getchar() != '\n')
instead if you want it to work with enter.
Upvotes: 7