Thread: this version of getchar/putchar removes a character from output

  1. #1
    Registered User
    Join Date
    Mar 2023
    Posts
    33

    this version of getchar/putchar removes a character from output

    So here is short/simple program that just takes your keyboard input, and outputs it when you press enter:

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    
    int main()
    {
       int c = getchar();
    
    
       while(c != EOF)
       {
          putchar(c);
          c = getchar();
       }
    }
    In "The C Programming Language" book, the author says doing this is more terse equivalent:

    Code:
    int main()
    {
       int c = getchar();
    
    
       while((c = getchar()) != EOF)
       {
          putchar(c);
       }
    }
    However, the behavior is slightly different, on the first input, it removes a character. I can't figure out why:

    Code:
    a
    
    abc
    abc
    

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > int c = getchar();
    > while((c = getchar()) != EOF)
    There are two calls to getchar before you get to your first putchar.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2023
    Posts
    33
    Quote Originally Posted by Salem View Post
    > int c = getchar();
    > while((c = getchar()) != EOF)
    There are two calls to getchar before you get to your first putchar.
    Lol, that's correct, so it "consumes" a character.

    Missing these little things makes me feel so dumb.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar() and putchar(c)
    By an96 in forum C Programming
    Replies: 5
    Last Post: 06-13-2015, 04:21 PM
  2. getchar() and putchar()
    By kawaikx15 in forum C Programming
    Replies: 5
    Last Post: 04-13-2011, 11:02 AM
  3. getchar putchar
    By chess2009 in forum C Programming
    Replies: 7
    Last Post: 03-06-2011, 02:44 AM
  4. need help please! getchar, putchar, etc.
    By sue in forum C Programming
    Replies: 1
    Last Post: 03-21-2003, 08:40 PM
  5. Replies: 2
    Last Post: 01-10-2002, 07:42 PM

Tags for this Thread