Thread: Using Scanf??

  1. #1
    Registered User
    Join Date
    Oct 2011
    Location
    Sivakasi
    Posts
    1

    Using Scanf??

    Code:
    #include <stdio.h>
    
    int main()
    {
    int a,b,c;
    char i;
    
    printf("Enter Two numbers\n");
    
    scanf("%d%d",&a,&b);
    
    scanf("%c",&i);
    
    printf("a to add\ns to Subtract");
    
    scanf("%c",&i);
    
    switch(i)
    {
    case 'a':
    c = a + b;
    printf("%d",c);
    break;
    
    case 's':
    c = a-b;
    printf("%d",c);
    break;
    
    default:
    break;
    }
    
    return 0;
    }
    in the above program to get the char i scanf is used two times. If using it for a single time the control jumps to the switch case after getting the integers a and b.

    Please explain the flow why this is happening.

    also explain the proper usage of scanf..

    Thanks and regards,
    Iyan

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    One other quick note to start. i is a horrible name for a char variable. Use the more common c or ch. By convention, i is an int variable*, and typically reserved for very basic stuff where a fancy name is actually unnecessary, like loop variables, array indexes or in mathematical equations.

    Also, your indentation needs work. Read this: SourceForge.net: Indentation - cpwiki. If you make it hard for us to read your code, we're less likely to help. Here's what your code should look like.
    Code:
    #include <stdio.h>
    
    int main()
    {
        int a,b,c;
        char i;
    
        printf("Enter Two numbers\n");
        scanf("%d%d",&a,&b);
        scanf("%c",&i);
        printf("a to add\ns to Subtract");
        scanf("%c",&i);
    
        switch(i)
        {
            case 'a':
                c = a + b;
                printf("%d",c);
                break;
    
            case 's':
                c = a-b;
                printf("%d",c);
                break;
    
            default:
                break;
        }
    
        return 0;
    }
    Quote Originally Posted by iyan90007 View Post
    in the above program to get the char i scanf is used two times. If using it for a single time the control jumps to the switch case after getting the integers a and b.

    Please explain the flow why this is happening.

    also explain the proper usage of scanf..

    Thanks and regards,
    Iyan
    If only I had a nickel for every time this question came up. You could (and should in the future) search our forums in case your question has been asked before. This one has probably been asked and answered once per week. Anyway, it's because after you type the numbers for a and b, you hit the enter key, which puts a new line ('\n') in the input buffer. When you use the %c modifier with scanf, it reads the newline as a character. Read FAQ article we have on alternatives: FAQ > Flush the input buffer - Cprogramming.com.

    * Note I said 'int' and not 'integer'. Technically, a char is a very small integer value (usually 1 byte, may be signed or unsigned), but i is typically a regular int (usually 4 or 8 bytes), which is always signed.
    Last edited by anduril462; 09-20-2012 at 01:29 AM. Reason: reworded

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Lets say you type in

    1 2\n
    a\n

    Your scanf on line 12 is to get rid of the first \n (after typing in your two numbers)

    The scanf on line 16 reads the a/s letter of your choice.

    %c is unique among the format conversions in that it does not automatically skip any leading white space.
    It always takes the next character.

    To get around this, you should be able to write
    Code:
    printf("Enter Two numbers\n");
    scanf("%d%d",&a,&b);
    
    printf("a to add\ns to Subtract");
    scanf(" %c",&i);  // note the leading space
    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.

  4. #4
    Registered User
    Join Date
    May 2011
    Posts
    30
    scanf is an evil function. getchar is much better.

  5. #5
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Another way of getting rid of the '\n' character is by asking the scanf to read a character and do nothing with it -> this is done by using the '*' after the %.

    i.e.
    Code:
    puts("Enter Two numbers\n");
    scanf("%d%d%*c",&a,&b);
    Fact - Beethoven wrote his first symphony in C

  6. #6
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    I forgot to mention that the 'c' at the end is because we are reading a character - You can do it with any scanf friendly data-type.

    See Format Specification Fields: scanf and wscanf Functions for more info on scanf
    Fact - Beethoven wrote his first symphony in C

  7. #7
    Time-Lord Victorious! The Doctor's Avatar
    Join Date
    Aug 2012
    Location
    Perth, Western Australia
    Posts
    50
    Quote Originally Posted by Shokwav View Post
    scanf is an evil function. getchar is much better.
    Can you explain why it is evil? I don't see a problem with it. (Though I am admittedly new to C)
    Code:
    if (codeWorks( code) && !youCanDoSomethingBetter( code) )
    {
         beHappy();
    } else
    {
         fixCode( code);
    }

  8. #8
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Eh, it's not really that evil, but it is very, very picky about input being in the right format. There's a lot of little things for a newbie to get caught up on. Many people will not recommend using scanf itself, but other functions in the scanf family (sscanf or fscanf) are okay. I often read a whole line of input from the user with something like fgets, then using sscanf to parse the line it read (the 's' is for string since that's where it gets it's input). fscanf is also useful if you have a file with a well-controlled format, like something generated by another program instead of a user file. Also, it's not a good idea to mix calls to scanf with other input functions like getchar or fgets(stdin).

  9. #9
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    This series may explain some of the pitfalls, and when scanf() should not be used.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf
    By Tool in forum C Programming
    Replies: 4
    Last Post: 02-23-2010, 03:21 AM
  2. Help with while's and scanf's...
    By m600 in forum C Programming
    Replies: 14
    Last Post: 01-19-2010, 03:31 PM
  3. First scanf() skips next scanf() !
    By grahampatten in forum C Programming
    Replies: 5
    Last Post: 08-17-2004, 02:47 AM
  4. scanf
    By beginner2003 in forum C Programming
    Replies: 5
    Last Post: 02-09-2003, 08:55 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM

Tags for this Thread