Thread: getchar() help

  1. #1
    Registered User
    Join Date
    Jun 2012
    Posts
    25

    getchar() help

    In the following code snippet

    Code:
    while(1)
        {
            char c;
            printf("enter y/n");
            c=getchar();
            if(c=='y')
                continue;
            else
                break;
        }
    the getchar() doesn't work in the second iteration.Why is that?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    it is working - it reads \n character that is left in the stream
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User
    Join Date
    Jun 2012
    Posts
    25
    Okay..is there any way to override that and keep the loop running until a char input 'n' is entered?

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well the problem is the solution in this case. Read all of the input. One getchar will read the interesting character, and another call will read the \n, which you are free to ignore.

  5. #5
    Registered User
    Join Date
    Apr 2013
    Location
    Still looking..
    Posts
    35
    Hmm I may be wrong, but aren't continue and break statements "forbidden" in if-else statements ?

  6. #6
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    No, the code makes sense.
    Code:
    while forever:
      if c is y:
        continue the loop
      else:
        break it
    end while

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. EOF value and getchar
    By Sharifhs in forum C Programming
    Replies: 3
    Last Post: 08-12-2010, 11:13 AM
  2. Why two getchar() ?
    By ekosix in forum C Programming
    Replies: 2
    Last Post: 06-05-2010, 01:13 PM
  3. Using getchar()
    By countchocula in forum C Programming
    Replies: 13
    Last Post: 04-23-2008, 08:07 AM
  4. getchar() and '\b'
    By snfiddy in forum C Programming
    Replies: 2
    Last Post: 11-30-2005, 05:52 PM
  5. getchar
    By pktcperlc++java in forum C++ Programming
    Replies: 4
    Last Post: 02-13-2005, 08:31 PM