Thread: How does getchar work in this example?

  1. #1
    c_beginner_
    Guest

    Post How does getchar work in this example?

    Hi!

    I'm working through K&R slowly and have encountered this example demonstrating getchar and putchar:

    Code:
    main()
    {
        int c;
    
        c = getchar();
        while (c != EOF) {
            putchar(c);
            c = getchar();
        }
    }
    I am confused how, each time getchar is called in the loop, it "remembers" which character it's up to in the text stream; how does it not just go straight back to the beginning of the text stream? If somebody could clarify how this works in this case, it would be greatly appreciated.

    Thanks!
    Last edited by c_beginner_; 03-27-2020 at 11:51 AM.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Think as the input text stream as a deck of cards.
    getchar removes the top card and returns its value.
    If there is no top card it returns EOF

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    c_beginner_
    Guest
    Quote Originally Posted by stahta01 View Post
    Think as the input text stream as a deck of cards.
    getchar removes the top card and returns its value.
    If there is no top card it returns EOF

    Tim S.
    Thank you for the explanation, this makes it easier to understand now.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 10-03-2018, 03:55 AM
  2. help with getchar()
    By nnannos in forum C Programming
    Replies: 2
    Last Post: 03-20-2016, 04:34 AM
  3. getchar() doesn't work
    By rhololkeolke in forum C Programming
    Replies: 9
    Last Post: 07-14-2007, 08:40 PM
  4. getchar() to work twice
    By bigboii in forum C Programming
    Replies: 2
    Last Post: 11-06-2005, 10:16 PM
  5. getchar
    By pktcperlc++java in forum C++ Programming
    Replies: 4
    Last Post: 02-13-2005, 08:31 PM

Tags for this Thread