Pelles C forum

C language => Beginner questions => Topic started by: ZeUsM on February 12, 2014, 11:03:14 AM

Title: Unexpected work of getchar() function
Post by: ZeUsM 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
#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?
Title: Re: Unexpected work of getchar() function
Post by: DMac 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:


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


And this will loop until EOF is encountered


char inChar;
for (;;)
{
  inChar = getchar();
  printf("%d\n", inChar != EOF);
  if(inChar == EOF) break; 
}
Title: Re: Unexpected work of getchar() function
Post by: ZeUsM on February 12, 2014, 08:55:47 PM
Yes, it is, but why in other compilers this construction works different?  :-\
Title: Re: Unexpected work of getchar() function
Post by: TimoVJL on February 12, 2014, 09:21:04 PM
Quote from: ZeUsM on February 12, 2014, 08:55:47 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.
QuoteIf 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