Brian Zhang
Brian Zhang

Reputation: 3

getchar() in C with while looping not printing afterwards

I don't understand why the printf() call after the while loop does not get executed?

int main(){
    while((getchar()) != EOF){
        characters ++;
        if (getchar() == '\n'){
            lines++;
        }
    }
    printf("lines:%8d\n",lines);
    printf("Chars:%8d",characters);

    return 0;
}

Upvotes: 0

Views: 442

Answers (3)

srilakshmikanthanp
srilakshmikanthanp

Reputation: 2399

I think you are trying to do that

#include<stdio.h>


int main()
{
    int characters=0,lines=0;
    char ch;

    while((ch=getchar())!= EOF)
    {

        if (ch == '\n')
            lines++;
        else
        {
            characters++;
            while((ch=getchar())!='\n'&&ch!=EOF);   //is to remove \n after a character
        }
    }

    printf("lines:%8d\n",lines);
    printf("Chars:%8d",characters);

    return 0;
}

Output:

a
s
d
f

^Z
lines:       1
Chars:       4
Process returned 0 (0x0)   execution time : 8.654 s
Press any key to continue.   

Note: ^Z(ctrl+z) is to send EOF to stdin (in windows)

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50882

You are probably looking for something like this:

#include <stdio.h>

int main()
{
  int characters = 0;
  int lines = 0;
  int c;
  while ((c = getchar()) != EOF) {
    characters++;
    if (c == '\n') {
      lines++;
      characters--;  // ignore \n
    }
  }
  printf("lines: %8d\n", lines);
  printf("Chars: %8d", characters);

  return 0;
}

while ((c = getchar()) != EOF) might look a bit confusing.

Basically it calls getchar, puts the returned valuee into c ands then checks if c equals EOF.

Upvotes: 0

cocool97
cocool97

Reputation: 1251

You have to be careful of you're treatment in the while loop. Indeed, you are missing every caracter read in your while statement. You have to save this input, in order to use it afterwards.
The proper syntax would be while(( c = getchar()) != EOF)

Upvotes: 1

Related Questions