#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    If loop conditions ignored


    I am trying to use the response to a yes/no question to print one of two strings:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int input;
        printf ("Does this program work? Y/N:");
        scanf("%i",input);
        if ((input == 'y') || (input == 'Y'))
        {
            printf ("Success");
        }
        else
        {
            printf ("Error");
        }
    }
    However, no matter what letter I put in, I get the "Error" result. I'm not sure what I'm doing wrong, so I'm seeing if anyone here can figure it out?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    It's pretty amazing that it doesn't crash.
    Code:
    $ gcc -W -Wall -Wextra foo.c
    foo.c: In function ‘main’:
    foo.c:8:5: warning: format ‘%i’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat]
    foo.c:17:1: warning: control reaches end of non-void function [-Wreturn-type]
    foo.c:8:10: warning: ‘input’ is used uninitialized in this function [-Wuninitialized]
    First of all, you forgot to use &input in your scanf call.

    Then you need to realise that %i isn't for typing in letters.

    You could type in 89 I suppose, but that's a bit counter-intuitive.
    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

IMN logo majestic logo threadwatch logo seochat tools logo