counting characters in the input with while loop - c

I wrote a simple c program to count number of characters
#include <stdio.h>
main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
This program is not printing me the characters. On testing different cases, I found that I am stuck in an infinite while() loop.

This program isn't printing me the characters
It won't. You did not add any statement to print them.
I found that i'm stuck in an infinite while loop
If you don't hit the breaking condition, you'll be in the loop. You need to get EOF to exit the loop. use
CTRL+Z (on windows)
CTRL+D (on linux)
Now, the solutions:
getchar() won't print the values. You have to store the values and print explicitly (if you want to) using , maybe putchar().
You either supply EOF or change the breaking condition of while() to come out of the essential infinite loop otherwise.
Apart from the coding issues, you need to think about the logic, too. In the present form of the code, getchar() counts the newline (\n) as a valid character, too. To explain, an input in the form of
$ ./a.out ENTER
a ENTER
s ENTER
d ENTER
f ENTER
g ENTER
CTRL+D
Will produce a result
10
but that is not what we generally call counting the character. You may want to review this part of the logic, too.
That said, the recommended signature of main() is int main(void).

Try the following
#include <stdio.h>
int main( void )
{
int c;
long nc = 0;
while ( ( c = getchar() ) != EOF && c != '\n' ) ++nc;
printf( "%ld\n", nc );
}
You have to generate the EOF state ( Ctrl+d in UNIX-systems or CTRL+z in Windows) or simply press Enter.

Try like this:
#include <stdio.h>
int main(void)
{
int c;
long nc = 0;
while ( ( c = getchar() ) != EOF && c != '\n' )
++nc;
printf( "%ld\n", nc );
}

while (getchar() != '\n')
++nc;
printf("%ld \n",nc);
Worked!

Related

C Simple Code Involving getchar() and putchar() Unexpected Output

As I was following an example from a book,
#include <stdio.h>
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c)
c = getchar();
}
}
I thought it would make more sense to read character first, then print it so switched putchar and getchar around
c = getchar();
putchar(c);
now when I run it, what happens is the first output of putchar is missing the first character of c? This is the output:
kingvon#KingVon:~/Desktop/C$ ./a.out
first letter is missing?
irst letter is missing?
but now it is not
but now it is not
This is interesting, why does this happen?
Because you're getting a character before the loop. That means c is equal to that first character, but in the loop it's getting every character after that. So,
Get: f
Start the loop
Get: i
Print: i
And so on
The problem is that now you're not printing the character that you read with getchar() before the loop, so you don't print the first character.
If you want to do the getchar() first, put it into the while() condition.
#include <stdio.h>
main()
{
int c;
while ((c = getchar()) != EOF) {
putchar(c)
}
}

Counting number of user input using getchar() gives double the expected result, why?

In the following example, from the book "C programming", when input characters, the program count twice.
main(){
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
OUTPUT:
a
b
c
d
e
f
12
What's wrong?
I'am using Ubuntu and the gcc compiler.
It's counting properly. getchar() is considering the ENTER key press also, as a newline \n. So 6 user inputs and 6 newlines. Counts match.
If you don't want the newlines to be counted as inputs, you need to increment the counter when the getchar() return value is not \n, something like
while ( (c = getchar()) != EOF) {
if ( c != '\n') ++nc;
}
will get the job done. Note, c should be of type int to be able to handle EOF.
That said, as per C99 or C11, for a hosted environment, the signature of main() should at least be int main(void) to conform to the standard.

How EOF really works in this one?

#include<stdio.h>
#include<conio.h>
int main() {
long nc;
nc = 0;
while (getchar()!= EOF){
++nc;
printf("%ld\n", nc);
}
return 0;
}
My question is: When I input a number or a character, it increments twice >.<
for example: I ran the program, I typed 1, then its going to output
1
2
can someone please tell me why >< cause isn't it suppose to just increment 1? And the value of nc that the program is gonna show is 1? Then its going to become 2 when i enter another number or character?
After entering any number you are pressing Enter key.
and as '\n' != EOF so it is running two times.
int main() {
long nc;
nc = 0;
while (getchar()!= '\n'){ // check for enter key here.
++nc;
printf("%ld\n", nc);
}
return 0;
}
When you input a number and press Enter key, an additional \n character passed to the standard input buffer. getchar reads that number leaving behind \n in the buffer. On next iteration of loop getchar reads \n before pressing any character by you and hence inside while for second time.Hence value is printed twice as \n is not there.
Use below while condition and this shall fix the issue.
while(getchar() != '\n');
This will eat up any number of \n.

Working of getchar and putchar or example in The C language 2nd Edition

CODE 1:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
CODE 2:
#include<stdio.h>
main( )
{
int c,d;
c=getchar();
d=getchar();
putchar(c);
putchar(d);
}
1) If
Input : bo
Output : bo
I got to know this in 2nd program that it stores both in variables c and d but where does it stores them in 1st program.
2)Pl. explain the working of first program why it repeats any word despite of its length that is more than one character.
3) From book i got to know that EOF is encountered whenever I enter or there is some error but even if I press enter this program doesn't stops but it prints nextline character again.
For question one, it stores them in c (but only one at a time). The code, better indented, is:
while ((c = getchar()) != EOF)
putchar(c);
so you can see that, for each character input into c, it outputs it as well. Keep in mind that syntax is the short form for:
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
so you can see each iteration of the loop gets the next character.
The second question, I assume you're asking why it works for any length input. That's because it doesn't care about the length. It's simply storing and echoing each individual character.
You could give it a billion characters if you like.
As to the third, you get back EOF for an error or end of file (CTRL-Z at the start of a line for Windows, usually CTRL-D under UNIX-like operating systems, unless you have some weird terminal characteristics set up).
If you were only interested in a line, you could use something like:
while ((c = getchar()) != '\n')
putchar(c);
putchar ('\n');
while ((c = getchar()) != EOF)
Reads the value from stdin until it encounters EOF(End Of File). So the same variable c stores different values read in different iterations.
In the second example only two variable ( of char type ) are there so it can read and store only two characters.

Is printf supposed to print out a 'long' value? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why doesn’t getchar() recognise return as EOF in windows console?
I'm trying to print out the value in the variable 'nc' in the next program:
int main()
{
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
Please tell me why is it not printing?
You don't have brackets in your while loop (this is why not using brackets leads to error prone software). Therefore, the value is getting incremented, but not printing.
Try:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{ // ADD THIS
++nc;
printf("%ld\n", nc);
} // AND THIS
}
otherwise, your code is essentially doing:
int main(int argc, char** argv)
{
long nc;
nc = 0;
while (getchar() != EOF)
{
++nc; // ENDLESSLY ADDING
}
printf("%ld\n", nc); // NEVER REACHED DUE TO WHILE LOOP.
}
Your while loop will continue to loop until you end the input using Control-D on Unix or Control-Z, Return on Windows. It will do this without printing anything because you did not use braces around the ++nc and printf.
You may also have problems with printf if you did not #include <stdio.h> at the top of your program. If the compiler does not know that printf is a varargs function, it will not format the argument list correctly when calling it.
after entering some inputs like
1
2 4
u must type ctrl + D since its the EOF ASCII equivalent.
Else modify the progeam and put
while(getchar()!='\r') (until you hit Enter)
What do you mean? It works:
./a.out
asdfsdfasdfasdfasddddddddddddddddddddddd
41
echo "Try to count this" | ./a.out
18
you have to stop reading characters from stdin by stopping the while loop of getchar
and then you will see the nc value printed
To do
EOF = CTRL + D (for Linux)
EOF = CTRL + Z (for Windows)

Resources