curious scanf problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • skooter
    New Member
    • Nov 2006
    • 7

    curious scanf problem

    I've got the following function

    void remDuplicate(FI NDFILE filey, int sim, char *filePath)
    {
    char ans;
    numFound++;

    printf("Found file %s that is %d%% the same as %s. Delete (Y/N)??\n", filePath, sim, filey.filename) ;
    scanf("%c", &ans);

    ans = tolower(ans);
    if (ans == 'y')
    {
    printf("Removin g file %s\n", filePath);
    unlink(filePath );
    numRemoved++;
    }
    printf("Continu ing.\n");
    return;
    }

    which gets called each time two files are found that are dupilcates. Yet scanf only takes input each second time (1st, 3rd, 5th calls etc..) Any thoughts ehy??
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    Originally posted by skooter
    I've got the following function

    void remDuplicate(FI NDFILE filey, int sim, char *filePath)
    {
    char ans;
    numFound++;

    printf("Found file %s that is %d%% the same as %s. Delete (Y/N)??\n", filePath, sim, filey.filename) ;
    scanf("%c", &ans);

    ans = tolower(ans);
    if (ans == 'y')
    {
    printf("Removin g file %s\n", filePath);
    unlink(filePath );
    numRemoved++;
    }
    printf("Continu ing.\n");
    return;
    }

    which gets called each time two files are found that are dupilcates. Yet scanf only takes input each second time (1st, 3rd, 5th calls etc..) Any thoughts ehy??
    scanf() with the conversion specification "%c" returns the next character in the input stream.

    so when you enter Y followed by the <enter> key the first scanf() returns Y the next scanf() returns the newline character (put in the stream by the <enter> key).
    The thing to do is to put a space before the %c to skip whitespace in the input, e.g.
    Code:
    	scanf(" %c", &ans);

    Comment

    • skooter
      New Member
      • Nov 2006
      • 7

      #3
      Thanks. Worked a treat!

      Comment

      • ssharish
        New Member
        • Oct 2006
        • 13

        #4
        well the alterntive for that can be soemthing like this

        Code:
        #include <stdio.h>
        #include <string.h>
        
        int main()
        {
            int ch;
            
            printf("Please enter [Y/N]\n?");
            ch = getchar();
            
            if('Y' == toupper(ch))
                printf("You eneter \"YES\"");
            else
                printf("You eneter \"NO\"");
            
            getchar();
            return 0;
        }
        
        /* my output
        Please enter [Y/N]
        ?Y
        You eneter "YES"
        
        Please enter [Y/N]
        ?n
        You eneter "NO"
        */
        ssharish

        Comment

        Working...