Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getchar() infinite loop [closed]

Tags:

c

input

eof

getchar

I’m starting to learn from "The C Programing Language" and one of the codes in the book is not working for me. This code suppose to count the number of characters using getchar().

Here is my code:

#include <stdio.h>

int main()
{
  long nc;

  nc = 0;
  while (getchar() != EOF)
        ++nc;
  printf("%1d\n", nc);

  return 0;
}

I try to run it and write some characters but when I press ENTER, it only starts a new line. It's like it’s never getting out of the loop.

like image 994
אבנר יעקב Avatar asked Nov 18 '25 09:11

אבנר יעקב


1 Answers

A newline is not an EOF. You’re confusing EOF and EOL.

When your press ENTER, getchar() receives a newline: \n, and your program counts it just like any other character.

Try pressing CTRL + D (Linux terminal) or CTRL + Z (Windows terminal) to send an empty input to your program, thus ending it.

You can also write your input to a file, and give this file to your program as input, like this:

./your_program < your_file

When your input comes from a file, an EOF is automatically sent to your program when reaching the end of the file. That’s because there is not more output to get from the file.

like image 82
Ronan Boiteau Avatar answered Nov 21 '25 00:11

Ronan Boiteau