Thread: bug with scanf and loops

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    15

    bug with scanf and loops

    Code:
    #include <stdio.h>
    
    int main()
    {
        int i;
        int a[1000];
        int x;
        int ret;
        int y;
        int ret2;
    
        printf("----type in numbers-----\n");
        for(i=0;i<1000;i++)
        {
            printf("value%i: ",i);
            ret = scanf("%d",&a[i]);
            printf("\n");
            if(ret == 0 || a[i] == -99990)
            {
                printf("what value do you want?");
                ret2 = scanf("%d",&y);
                printf("\n");
                if(ret2 == 0)
                {
                    printf("bad input\n");
                    return 0;
                }
                else
                {
                    printf("good input bye");
                    return 0;
                }
    
    
            }
        }
        return 0;
    
    }
    I'm having a little bug where I'm asking the user to go in a loop and type in 1000 numbers into an array. if the user types in a letter or numbers with letters, the loops will automatically assign ret2 = 0 and it'll go into the bad input. But if i type in -99990, it'll let me go to the ret2 scanf. Is there a reason why it automatically make ret2 = 0 when I put in a letter?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Things that get typed in, but not read, will stay in the input stream until they are read. If you type something that isn't a number, then both your scanf calls will fail (scanf does not ask for more input if there is still input waiting in the stream). You should check out the FAQs about how to get bad input out of the input stream.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. converting for loops to while loops
    By nabhatt in forum C Programming
    Replies: 3
    Last Post: 02-16-2012, 09:45 PM
  2. Replies: 3
    Last Post: 06-01-2011, 04:19 PM
  3. loops, menu loops
    By gloworm in forum C Programming
    Replies: 17
    Last Post: 04-12-2010, 07:59 PM
  4. 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
  5. A question about loops and scanf
    By mzkhadir in forum C Programming
    Replies: 3
    Last Post: 10-04-2001, 10:35 AM