Thread: Value of variable stuck as '1'. Newbie help.

  1. #1
    Registered User
    Join Date
    Nov 2020
    Posts
    2

    Question Value of variable stuck as '1'. Newbie help.

    --SOLVED--

    Hey everyone, i'm new to coding (just started my degree in electrical engineering and coding in C is part of it).

    I'm trying to create and test a simple menu where the user can select options 1-4 and I set up two printf tests (1 within the function and 1 in the main function) to display the chosen option. x however is always shown has having the value of '1' and will not update to the choice. What have I done wrong? Thanks in advance!

    Code:
    #include <stdio.h>
    
    
    int pay_select(void);
    
    
    void main(void)
    {
        int choice = pay_select(); //run function where user selects option 1-4
        printf("Test 2 = %d", choice); //print selected option
        
    }
    
    
    int pay_select(void)
    {
        int x;
        puts("opt 1 = £5"); //pay options
        puts("opt 2 = £10");
        puts("opt 3 = £15");
        puts("opt 4 = £20");
        
        x = scanf("%d", &x); //saves option selected
        printf("Test 1 = %d\n", x);
        return x;
    }
    Last edited by bigchungus500; 11-04-2020 at 06:35 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > x = scanf("%d", &x); //saves option selected
    The x (on the left) is the return result of scanf, which is the number of conversions that scanf performed.
    Since you only have one format conversion in your format string, your choice of return result is 1 (success), 0 (no conversion) or EOF.

    Try with just this to begin with.
    scanf("%d", &x);
    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.

  3. #3
    Registered User
    Join Date
    Nov 2020
    Posts
    2
    That worked a charm! Thanks for the help. It seems such an obvious mistake now, but this had me scratching my head for a good hour.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Programming Help.....Newbie Stuck and Confused!!
    By gsxride in forum C Programming
    Replies: 2
    Last Post: 07-18-2011, 09:17 PM
  2. Iterate variable (newbie)
    By Roffemuffe in forum C Programming
    Replies: 5
    Last Post: 10-15-2008, 07:50 AM
  3. Newbie: Stuck on some Math
    By filicudi in forum C Programming
    Replies: 15
    Last Post: 09-01-2008, 07:47 AM
  4. newbie variable question
    By 182 in forum C++ Programming
    Replies: 7
    Last Post: 04-20-2006, 11:39 AM
  5. Newbie - file i/o - I'm stuck
    By djacko in forum C++ Programming
    Replies: 1
    Last Post: 02-22-2002, 09:56 AM

Tags for this Thread