Thread: shorthand if else

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    12

    shorthand if else

    Hi.
    my code isnt running, i think it may have something to do with the first printf and scanf functions. How do i transfer the inputted number to the following statement and have it run properly.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int cookies;
        printf("How many cookies to you have?");
        scanf("%d", cookies);
    
    
        printf("I have %d cookie%s",cookies, (cookies!= 1) ? "s" : "");
    
    }

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    In the scanf(), you need a '&' in front of "cookies" to pass the address of the int, not the value.

    Your printf() should have a '\n' after "cookie%s".

  3. #3
    Registered User
    Join Date
    Apr 2017
    Posts
    12
    haha i can't believe i missed that, thanks man!

  4. #4
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    1,111
    Quote Originally Posted by Tokalosh View Post
    haha i can't believe i missed that, thanks man!
    Most experienced programmers would never admit to the dumb mistakes we all make! ;^)

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Using a decent compiler with lots of warnings enabled traps all your printf/scanf mistakes.
    Code:
    $ gcc -Wall foo.c
    foo.c: In function ‘main’:
    foo.c:7:11: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
         scanf("%d", cookies);
               ^
    foo.c:7:5: warning: ‘cookies’ is used uninitialized in this function [-Wuninitialized]
         scanf("%d", cookies);
         ^
    $
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. While loop shorthand
    By RunDosRun in forum C Programming
    Replies: 1
    Last Post: 07-29-2007, 07:19 PM

Tags for this Thread