user3786923
user3786923

Reputation: 61

Counting the characters in C

Ive just started with programming and im using a Codeblocks compiler. With this code

long x = 0;

while(getchar() != EOF){
    ++x;
}

printf("%ld\n", x);

I am trying to count the characters of the input, but everytime I run the program it does not print anything at all.

However, this version

long x = 0;

while(getchar() != EOF){
    ++x;

printf("%ld\n", x);
}

prints the number of characters succesfully, but on the other hand it counts every single character(it shows me 1,2,3,4 instead of just 4).

Thank you for your answers.

Upvotes: 1

Views: 174

Answers (2)

Taimour
Taimour

Reputation: 459

Actually you are using EOF in while loop which means "end of file", it is basically used when you want to read from a text file. Now I explain you what is happening in your both codes than I will tell you how to solve it.

First code:

long x = 0;

while(getchar() != EOF){
   ++x;
}

printf("%ld\n", x);

Here you are taking input from the keyboard as long as EOF doesn't occur and once EOF occurs than loop will break and printf() will be executed but in this case EOF will not occur and as a result nothing will be printed.

Second code:

long x = 0;

while(getchar() != EOF){
   ++x;
printf("%ld\n", x);
}

The loop will continue as long as EOF doesn't occur and will keep on printing the value of x because printf() is present inside the while loop, so printf() will be executed as many times as the loop iterates.

Solution: Replace EOF with something else, any other character eg a space like this

long x = 0;

while(getchar() != ' '){
    ++x;
}

printf("%ld\n", x);

Upvotes: 1

nmio
nmio

Reputation: 798

How are you running the program, and how are you supplying the input? My assumptions are the following:

  1. You are running the program via a terminal
  2. The program wont actually end until you hit ctrl + c, and you expect
  3. You are supplying input by typing characters via the keyboard

If these are true, you will need to type the EOF character (ctrl + z on Windows, ctrl + d on Mac, probably the same on other unix). Alternatively, you can feed the program a file by using the < file.ext syntax. For example: ./a.out < input.txt

Upvotes: 4

Related Questions