NO

Author Topic: Unexpected work of getchar() function  (Read 3018 times)

ZeUsM

  • Guest
Unexpected work of getchar() function
« on: February 12, 2014, 11:03:14 AM »
Hi all!

I'm a beginner in C programming.
I have a problem with compiler or maybe it's incorrect work of function putchar().
So, I run the programm like this
Code: [Select]
#include <stdio.h>

int main(void)
{
 for (;;)
 {
  printf("%d\n", getchar()!=EOF);   
 }
}
and after I put ^Z my programm prints 0 as a loop without break, but the exact same code compiled with other compilers like MSVC and MinGW works different. Programm just prints 0 once. Where could my mistake be?

Offline DMac

  • Member
  • *
  • Posts: 272
Re: Unexpected work of getchar() function
« Reply #1 on: February 12, 2014, 06:28:22 PM »
You have not defined the condition to break the loop.

The following will continue to loop while an entered character is EOF but exit after any other char:

Code: [Select]
char inChar;
 for (;;)
 {
  inChar = getchar();
  printf("%d\n", inChar != EOF);
  if(inChar != EOF) break; 
 }

And this will loop until EOF is encountered

Code: [Select]
char inChar;
 for (;;)
 {
  inChar = getchar();
  printf("%d\n", inChar != EOF);
  if(inChar == EOF) break; 
 }
No one cares how much you know,
until they know how much you care.

ZeUsM

  • Guest
Re: Unexpected work of getchar() function
« Reply #2 on: February 12, 2014, 08:55:47 PM »
Yes, it is, but why in other compilers this construction works different?  :-\

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: Unexpected work of getchar() function
« Reply #3 on: February 12, 2014, 09:21:04 PM »
Yes, it is, but why in other compilers this construction works different?  :-\
They don't read document n1570.pdf or n1124.pdf
Pelle have opportunity follow those documents, so don't blame him.
Quote
If the standard input was at the end-of-file, the function returns EOF and sets the eof indicator (feof) of stdin.
In my simple mind i think that next input should be EOF ?

BTW: MSVC and MinGW gcc use msvcrt.dll
« Last Edit: February 12, 2014, 09:41:55 PM by timovjl »
May the source be with you