CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: C: getchar

  1. #1
    Join Date
    Jun 2012
    Posts
    58

    C: getchar

    hi,

    once again i hit a very simple problem i am unable to resolve. I using Visual Studio 2010, but am compiling for C.


    THis:
    Code:
    	char i=45;
    	while(i=getchar() != EOF)
    	{

    should imo work perfectly (yes, no real code, just to demonstrate the issue), but it doesnt. Getchar() always returns 0x01. Why is that?
    This, in contrast, works perfectly fine:

    Code:
    	char i=45;
    
    	while(i!= EOF)
    	{
    i=getchar();
    Shouldnt an assignment always return the assigned value?

  2. #2
    Join Date
    Aug 2009
    Posts
    440

    Re: C: getchar

    When you do:
    Code:
    while( i = getchar() != EOF )
    You are really doing:
    Code:
    while( i = ( getchar() != EOF ) )
    So, it gets the character, compares it against the EOF character. It's most likely not equal to it, and so that boolean will become 1 and get assigned to i. This happens because the != operator has a higher precedence than the assignment operator.

  3. #3
    Join Date
    Oct 2002
    Location
    Austria
    Posts
    1,284

    Re: C: getchar

    There is another problem with your code.
    EOF is usually defined as the int -1. If you assign it to a char then the value will be truncated and the test will never be true.
    BTW that is the reason why getchar() returns an int and not a char.
    Kurt

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured