Thread: scanf issue

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    662

    scanf issue

    hi all complete newbie here im just trying to practice some stuff i have learnt so far and have come across an issue i have no clue as to why it is happening.

    i have some code that asks the user a yes or no question and acts apon the answer ie
    Code:
    printf("are you male\n");
    scanf("%c",&yn);
    if (yn=='y')
    {
          //do suff
    }
    
    printf("are you tall\n");
    scanf("%c",&yn);
    if (yn=='y')
    {
          //do suff
    }
    return 0;
    doesn't ask for input on the second scanf it just exits the program

    however .....

    Code:
    scanf("%c",&yn); //why this extra scanf
    printf("are you tall\n");
    scanf("%c",&yn);
    if (yn=='y')
    {
          //do suff
    }
    return 0;
    works as in a get asked to enter y or n a second time.

    any help would be appreciated
    many thanks
    coop

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    717
    Did you notice the name of the funcion? scanf?!

    When you ask to scanf() to get a single char ("%c") from the input stream (stdin) and you type 'y' followed by ENTER ('\r'). BOTH characters are in the stream... If you want ignore "space" chars (' ', '\r', '\n', '\t', '\f' and '\v' - as checked by isspace() macro on ctype.h), add a single space after %c.

  3. #3
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,875

  4. #4
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    738
    Quote Originally Posted by flp1969 View Post
    Did you notice the name of the funcion? scanf?!

    When you ask to scanf() to get a single char ("%c") from the input stream (stdin) and you type 'y' followed by ENTER ('\r'). BOTH characters are in the stream... If you want ignore "space" chars (' ', '\r', '\n', '\t', '\f' and '\v' - as checked by isspace() macro on ctype.h), add a single space after %c.
    The "ENTER" char is '\n', (newline), NOT '\r', (carriage return)!

  5. #5
    Registered User
    Join Date
    Feb 2019
    Posts
    717
    Quote Originally Posted by rstanley View Post
    The "ENTER" char is '\n', (newline), NOT '\r', (carriage return)!
    Nope... '\r' (13) is the "enter" char... The system translate it to '\n' (10).

    The symbol for "Enter" on the keyboard is ⏎ (carriage return).

  6. #6
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    738
    Quote Originally Posted by flp1969 View Post
    Nope... '\r' (13) is the "enter" char... The system translate it to '\n' (10).

    The symbol for "Enter" on the keyboard is ⏎ (carriage return).
    The subject of this thread is data received using "scanf(), NOT keyboard keycodes!!!

    When using scanf(), and I enter 'y', then press the [Enter] key on the keyboard, the two characters in the input buffer are, "y\n", the '\n' character is a 0x0a hex, or the '\n' character.

    It is the '\n' that needs to be removed after receiving the 'y'.
    Last edited by rstanley; 04-14-2019 at 08:32 PM.

  7. #7
    Registered User
    Join Date
    Apr 2019
    Posts
    3

    Re: scanf issue

    Code:
    #include <stdio.h>
    
    int main()
    {
        char yn;
    
        printf("Are you male? ");
        scanf("\n%c", &yn);
        if (yn == 'y')
            printf("You're a boy!\n");
        else
            printf("You're a girl!\n");
        printf("\n");
    
        printf("Are you tall? ");
        scanf("\n%c", &yn);
        if (yn == 'y')
            printf("You're tall!\n");
        else
            printf("You're short!\n");
    
        return 0;
    }

    For some reason, typing scanf("\n%c", &yn); provides me the chance to input the value for char yn; once the second question is asked. I'm not too sure why it is like that, however. Of course, I could be wrong and/or there might be a better workaround for this so take my solution with a grain of salt for now. I'm a complete newbie when it comes to the C language.

    If anyone wants to chime in as to why my solution appears to be working and/or can tell me what I can do to improve on this, let me know! I've only completed the introductory material on C's tutorial page, so I haven't quite got around to understanding why this works on my end or anything.

    EDIT:
    Quote Originally Posted by Click_here View Post
    I am only now reading about this, I should have skimmed through the replies to this thread better before posting up my own.
    Last edited by bozware; 04-14-2019 at 08:22 PM. Reason: N/A

  8. #8
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    738
    Change:
    Code:
    scanf("\n%c", &yn);
    with
    Code:
    scanf(" %c", &yn);
    Using a space instead of the explicit '\n' will make scanf() ignore any possible whitespace characters before inputting the legitimate char you want.

    Now you need to handle inputting uppercase 'Y' or 'N', or characters other than 'y' or 'n'.

    I would also recommend a good book on the C Programming language. The tutorials on this site are limited.

  9. #9
    Registered User
    Join Date
    Feb 2019
    Posts
    717
    Quote Originally Posted by rstanley View Post
    The subject of this thread is data received using "scanf(), NOT keyboard keycodes!!!

    When using scanf(), and I enter 'y', then press the [Enter] key on the keyboard, the two characters in the input buffer are, "y\n", the '\n' character is a 0x0a hex, or the '\n' character.

    It is the '\n' that needs to be removed after receiving the 'y'.
    It doesn't matter if it is '\r' o '\n', a single space following %c will ignore both... AND, it is not a "key code". Technically speaking, the scan code from the keyboard for the ENTER key is 0x5A or 0xED5A:

    scanf issue-scancodes-png

    My point: ENTER is '\r', translated to '\n' from the keyboard scan codes...
    Last edited by flp1969; 04-14-2019 at 08:54 PM.

  10. #10
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    738
    Once again!!!

    This thread is about scanf(), NOT "keyboard scan codes..."!

    Please stick to the subject of the OP. Please do not confuse the OP who is a beginner!

  11. #11
    Registered User
    Join Date
    Apr 2019
    Posts
    3

    Re: scanf issue

    Quote Originally Posted by rstanley View Post
    Change:
    Code:
    scanf("\n%c", &yn);
    with
    Code:
    scanf(" %c", &yn);
    Using a space instead of the explicit '\n' will make scanf() ignore any possible whitespace characters before inputting the legitimate char you want.

    Now you need to handle inputting uppercase 'Y' or 'N', or characters other than 'y' or 'n'.

    I would also recommend a good book on the C Programming language. The tutorials on this site are limited.
    Code:
        char yn;
    
        printf("Are you male? ");
        scanf(" %c", &yn);
        do {
            switch (yn) {
            case ('y'):
                printf("You're a boy!\n");
                yn = ' ';
                break;
            case ('Y'):
                printf("You're a boy!\n");
                yn = ' ';
                break;
            case ('n'):
                printf("You're a girl!\n");
                yn = ' ';
                break;
            case ('N'):
                printf("You're a girl!\n");
                yn = ' ';
                break;
            default:
                printf("Are you male? ");
                scanf(" %c", &yn);
            }
        } while (yn != ' ');
    This is only assuming that the end-user types in a single character, though I suppose I'll need to learn how to either flush the input buffer or parse additional values as mentioned from this link at some point.

    And I agree, I'll definitely be looking into one of the recommended books soon for this language.

  12. #12
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,875
    A good way of handling input is by using fgets and then using sscanf on the buffer.
    After that you can also do things like handle double presses...
    Code:
    if ((inputBuffer[0] == 'y') && (inputBuffer[1] == '\n'))
    {
      ...
    }


    Code:
            printf("Are you male? ");
            scanf(" %c", &yn);
    Not a big issue, but the output stream isn't guaranteed to write the data out immediately.
    fflush(stdout)
    c - Why does printf not flush after the call unless a newline is in the format string? - Stack Overflow
    The fix to that is to use fflush(stdout)

    You may also want to work on your variable names: 'yn' is not a very good one. You may want to call the variable 'userInput' / 'userResponse' / 'genderInput' / ect...

    Hope this helps
    Fact - Beethoven wrote his first symphony in C

  13. #13
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,875
    though I suppose I'll need to learn how to either flush the input buffer ...
    Flush the input buffer - Cprogramming.com
    Fact - Beethoven wrote his first symphony in C

  14. #14
    Registered User
    Join Date
    Feb 2019
    Posts
    717
    Quote Originally Posted by rstanley View Post
    Once again!!!

    This thread is about scanf(), NOT "keyboard scan codes..."!

    Please stick to the subject of the OP. Please do not confuse the OP who is a beginner!
    Ok... but why did YOU bring the subject on #3?

  15. #15
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    738
    Quote Originally Posted by flp1969 View Post
    Ok... but why did YOU bring the subject on #3?
    I was originally responding to posting #2, by you, then you got into an off-topic discussion about keyboard scancodes.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Scanf Issue with Segmented input(?)
    By capitalCORN in forum C Programming
    Replies: 4
    Last Post: 10-22-2014, 02:07 PM
  2. scanf issue - character in buffer
    By demps in forum C Programming
    Replies: 2
    Last Post: 01-19-2010, 07:51 PM
  3. Issue with scanf and char
    By Covalent in forum C Programming
    Replies: 6
    Last Post: 11-03-2008, 12:06 AM
  4. 'cin' and 'scanf()' issue
    By Brain Cell in forum C++ Programming
    Replies: 4
    Last Post: 11-07-2004, 10:53 AM
  5. scanf issue
    By fkheng in forum C Programming
    Replies: 6
    Last Post: 06-20-2003, 07:28 AM

Tags for this Thread