Thread: How to capture <return>/<enter> in C

  1. #1
    Registered User
    Join Date
    Jan 2024
    Posts
    2

    How to capture <return>/<enter> in C

    Folks,
    I have look at the other threads, and they say to capture the value returned by scanf to see if the user just hit the enter key.
    I get nothing back if I just hit enter...
    When I enter a single character then enter, I get a returned value of 1.
    Here is the code snippet:
    printf ("Please give me a single digit number >> "];
    Number = getchar ();

    while (getchar() != '\n');

    here is the oputput from just entering return:


    Give me one, single, letter, please >>
    |

    Note: The cursor drops to the following line, but the program hangs waiting for "something" to read. I need to capture the enter and I'm stumped. Can the wizards help. No, this isn't for an assignment, I'm the professor and I want to demonstrate this, along with other uses of ctype.h. This one is hanging me up.

    [COLOR=rgba(255, 255, 255, 0.85)]
    [/COLOR]
    Last edited by DocG; 01-30-2024 at 11:55 PM. Reason: To get rid of the HTML color codes

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,675
    Seems simple enough.
    Code:
    #include <stdio.h>
    int main(void)
    {
        int ch, number;
        printf ("Please give me a single digit number >> ");
        number = getchar ();
        while ((ch=getchar()) != '\n') {
            printf("Ate '%c' for breakfast\n",ch);
        }
        printf("You typed a '%c'\n", number);
    }
    
    
    $ gcc foo.c
    $ ./a.out 
    Please give me a single digit number >> 3a
    Ate 'a' for breakfast
    You typed a '3'
    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
    Jan 2024
    Posts
    2

    Fixed it. Thank you.

    Found the problem, hidden getchar(). Sorry

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 04-07-2007, 11:11 AM
  2. Capture Enter key press in EDIT Box
    By richiev in forum Windows Programming
    Replies: 4
    Last Post: 07-14-2005, 12:03 AM
  3. Hit Enter, Return mainscr();
    By stickman in forum C++ Programming
    Replies: 6
    Last Post: 08-24-2004, 05:49 PM
  4. Need to capture the enter key
    By tyouk in forum Windows Programming
    Replies: 7
    Last Post: 11-08-2003, 06:07 PM
  5. Making the Enter Key do a Return
    By BigSter in forum C++ Programming
    Replies: 7
    Last Post: 05-25-2002, 12:09 PM

Tags for this Thread