Gon
Gon

Reputation: 41

Counting number of lines in input string in C

Here's my problem-

char c,int nl=1;
printf("Enter string");
while((c=getchar()) != EOF)
{
   if(c=='\n')
      ++nl;
}
printf("Number of lines=%d",nl);


No error. But when I give input it continues to take input (do not comes out of console screen). Why compiler is unable to read EOF value ? I also tried while((c=getchar())!='\0') but doesn't work !

Upvotes: 2

Views: 984

Answers (2)

Marievi
Marievi

Reputation: 5001

You should declare c as int instead of char.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

char is not capable to store EOF. Use int to store the return value of getchar().

Try changing

char c,int nl=1;

to

int c,nl=1;

Upvotes: 1

Related Questions