Using getchar()

This is a discussion on Using getchar() within the C Programming forums, part of the General Programming Boards category; Hello I am trying to make a function that requires the user to press the enter key to continue. The ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    19

    Using getchar()

    Hello I am trying to make a function that requires the user to press the enter key to continue.

    The function that I want to work looks like this:

    Code:
    void ent (void)
    {
      printf("Press Enter: ");
      while( getchar() != '\n' );
    }

    I have been fiddling around with different versions of this particular code, but every time I call this function it runs the printf statement but never lets me enter any key, let alone the enter key. I think I am not understanding something about getchar().

    I have seen a similar example doing an internet search and their code is in the same vein and did exactly what I want, but it just won't work for me. Any ideas?


    EDIT:

    Here is the code that I found on my google search that essentially does what I want:
    Code:
    #include <stdio.h>
    
    int main()
    {
        int i;
    
        for (i = 0; i < 3; i++) {
            printf("i = %d\n", i);
            printf("Press 'Enter' to  continue: ... ");
            while ( getchar() != '\n')
                ;
        }
        printf("\n\n");
        printf("Ttttthat's all, folks\n");
        printf("Press 'Enter' to exit the program ( ironic, isn't it?) ...");
        while (getchar() != '\n')
            ;
        printf("\n\n");
        printf("Ttttthat's really all!\n");
        return 0;
    }
    http://www.gidforums.com/t-12871.html

    This code works as a standalone program, but when I try to use the same technique in my code, the while loop appears to be skipped.
    Last edited by countchocula; 04-22-2008 at 05:24 PM.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    You might need a fflush() after the printf(), since you don't have a newline (\n) at the end of your output string, which would automatically flush the output stream.
    Code:
    void ent (void)
    {
      printf("Press Enter: ");
      fflush(stdout);
      while( getchar() != '\n' );
    }

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    Quote Originally Posted by swoopy View Post
    You might need a fflush() after the printf(), since you don't have a newline (\n) at the end of your output string, which would automatically flush the output stream.
    Code:
    void ent (void)
    {
      printf("Press Enter: ");
      fflush(stdout);
      while( getchar() != '\n' );
    }


    Nope still doesn't work. It just prints "Press Enter" and then terminates.

  4. #4
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    Is there anyone else who can try to help me? This is so frustrating. I must not understand what getchar() is doing, because it works for the other guy's code, but it does not work for mine when I try to imitate it.

  5. #5
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    It works for me.
    Mac and Windows cross platform programmer. Ruby lover.

    Quote of the Day
    12/20: Mario F.:I never was, am not, and never will be, one to shut up in the face of something I think is fundamentally wrong.

    Amen brother!

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    Any ideas why it won't work for me?

    I want to use this function in a much larger program, but whenever I call the ent function it simply prints "Press enter" and then exits the function, thereby exiting the program.

  7. #7
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,246
    Quote Originally Posted by countchocula View Post
    Code:
    void ent (void)
    {
      printf("Press Enter: ");
      while( getchar() != '\n' );
    }
    There's no problem with this code -- aside from assuming that pressing ENTER will actually generate a '\n', which is by no means guaranteed (although incredibly likely).

    You must have a higher level bug.

  8. #8
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,246
    Quote Originally Posted by countchocula View Post
    Any ideas why it won't work for me?

    I want to use this function in a much larger program, but whenever I call the ent function it simply prints "Press enter" and then exits the function, thereby exiting the program.
    Oh. Well you didn't state that in your original question. You said it "does nothing" which is something entirely different. EDIT: Okay, it's my fault for not reading carefully enough -- you said the while loop appears to be skipped.

    What's happening is a '\n' is still sitting in the input buffer from some prior piece of input, and the function is consuming it immediately. This is a FAQ question.

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Let me guess ... you have a scanf() somewhere in your code.

  10. #10
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    Quote Originally Posted by swoopy View Post
    Let me guess ... you have a scanf() somewhere in your code.
    Yes, I do.


    I understand that I'm a noob, but I am trying to teach myself C with no other programming experience.

    Why is this a problem and how can I fix it? Thanks.

  11. #11
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    Quote Originally Posted by brewbuck View Post
    Oh. Well you didn't state that in your original question. You said it "does nothing" which is something entirely different. EDIT: Okay, it's my fault for not reading carefully enough -- you said the while loop appears to be skipped.

    What's happening is a '\n' is still sitting in the input buffer from some prior piece of input, and the function is consuming it immediately. This is a FAQ question.
    How can I clear the buffer or remove the '\n'? I have looked through the FAQ and I can't seem to find the thread explaining this.

    I know this seems like such a simple piece of code (and it is - which is why the issue is so annoyingly frustrating) but the problem that I am encountering seems to be much deeper than this piece of code would imply.

    I have considered just giving up on this function and trying something new, but I feel like there is something important to be learned from this issue. Thanks for your help.

  12. #12
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Why is this a problem and how can I fix it? Thanks.
    Because after scanf() reads in its parameters, it leaves the newline the user typed in the buffer. Now the simple solution to this is to add a loop like you posted after any call to scanf():
    Code:
    while (getchar() != '\n');
    However a better method which is recommended in the FAQ is to use fgets (with stdin as the file) to read in a line of input, followed by sscanf() to store the data.

  13. #13
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,246
    Quote Originally Posted by countchocula View Post
    I have considered just giving up on this function and trying something new, but I feel like there is something important to be learned from this issue. Thanks for your help.
    Giving up on it would be pointless, since the problem lies elsewhere. The code in question is fine.

    What's happening is something similar to this: You request input from the user.

    Code:
    printf("Enter a number: ");
    scanf("%d", &x);
    The user types 5 and presses enter. Now there are TWO characters in the input buffer: the digit '5', and a '\n' which was produced when they hit enter. The scanf() consumes the '5' but leaves the '\n' in the buffer.

    At this point if you call your ent() function, there is already a '\n' available in the buffer, it finds it, consumes it, and immediately returns.

    The problem was the failure to remove the previous '\n' from the buffer. The FAQ will explain in more detail.

  14. #14
    Registered User
    Join Date
    Apr 2008
    Posts
    19
    I got it working. It's because I was using scanf. I usually use fgets anyway, but I suppose I was being lazy when writing some portions of my code. I removed the scanf calls and now it works beautifully. Thanks for the help guys.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. getchar() problem
    By jlharrison in forum C Programming
    Replies: 6
    Last Post: 01-25-2006, 01:49 PM
  2. getchar buffer size
    By oncemyway in forum C Programming
    Replies: 3
    Last Post: 08-02-2005, 12:49 AM
  3. getchar() problem from K&R book
    By anemicrose in forum C Programming
    Replies: 13
    Last Post: 04-04-2004, 11:06 PM
  4. help with getchar lol
    By Taco Grande in forum C Programming
    Replies: 5
    Last Post: 03-18-2003, 08:25 PM
  5. Can anybody take a look at this?
    By TerryBogard in forum C Programming
    Replies: 10
    Last Post: 11-21-2002, 12:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21