-1

I was reading Kernighan Ritchie and there's this Character counting program, so I tried implementing

#include <stdio.h>
#include <stdlib.h>

int main()
{
char c;
int i;
c = getchar();
while (c != EOF)
    i= i + 1;
printf("%d",i);
}`

When I compile and run this code, after I enter some characters there's no output after that. No number is printed and I can't figure out why. The code looks fine. I also tried using scanf() but the same thing happened.

The next example was for counting lines in input and the same problem was there too.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user127
  • 23
  • 3

4 Answers4

7

In your code, when you're hitting

 i= i + 1;

the initial value of i is indeterminate. So, the whole program invokes undefined behavior. You need to initialize i.

To elaborate, i being an automatic local variable, unless initialized explicitly, the content is indeterminate. Using an indeterminate value in this case will lead to UB.

That said, a char is not able to hold a value of EOF, change the type to int.


After that, you're wrong in the logic. getchar() is not a loop on it's own, you need to keep calling getchar() inside the while loop body to update the value of c, used in the condition check in while.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • oops, yes I assigned 0 to i but that didn't solve the problem and neither did changing type of variable c to int. I have edited the question. – user127 Feb 20 '17 at 15:01
  • ... and [`getchar`](http://www.cplusplus.com/reference/cstdio/getchar/) returns an `int`, not a `char`. – Jabberwocky Feb 20 '17 at 15:38
2
int main()

Good. Not main() and not void main(). Keep it this way.

{
char c;

Bad. getchar() returns an int.

int i;

Bad. Not initialised, value is indeterminate. You are going to increment -7445219, or perhaps a kidney pie, who knows.

c = getchar();

Ok you have read a single character.

while (c != EOF)

But you cannot compare it to EOF because EOF doesn't fit in a char.

    i= i + 1;

Looks like you forgot to do something in the body of the loop. Something that is going to change c perhaps so that your loop has a chance to finish.

printf("%d",i);

It is recommended to add a newline to the last line of your output.

}

That's all folks.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
1

You only need to add an inicialization for "i"

int i = 0;

0

You missed the initialization:

int i = 0;