Thread: scanf help, returning incorrect value

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    4

    scanf help, returning incorrect value

    Hi there,

    I'm working on an assignment where I have to write a program that takes a user's order by prompting for customer number, for example:

    Enter the customer number (0 to quit):

    For each customer number entered displays the following menu to the user:

    A - Enter weight of artichokes
    B - Enter the weight of beets
    C - Enter the weight of carrots
    Q - Exit the ordering process for customer customerNumber
    Enter option:

    When the order for the customer is entered, the program has to compute the total charges, the discount, the shipping charges, and the grand total. The program should then display all the purchase information: the cost per kg, the kilograms ordered, and the cost for that order for each vegetable (if the vegetable was not ordered, then do not include it in the display), the total cost of the order, the discount (only if there is one), shipping weight, the shipping charge, and the grand total of all the charges.
    The program will then prompt the user for the next customer number, until a customer number of 0 (zero) is entered. The program will then display the total weight of each vegetable ordered for all customers and the total sales of all shipments.

    Now that you know what I'm up against, take pity on a poor noob and take a look at the first problem I'm having (I have a feeling I am slightly out of my league):

    Code:
    #include <stdio.h>
    
    int getCustomer(int custNo);
    
    
    int main(void)
    {
      int custNo;
    
    
      getCustomer(custNo);
      printf("Customer number: %d\n", custNo);
    }
    
    
    int getCustomer(int custNo)
    {
      printf("Enter the customer number (0 to quit):\n");
      scanf("%d",&custNo);
      while(custNo<0)
      {
          printf("Invalid customer number, please re-enter.");
          scanf("%d\n", &custNo);
      }
      printf("Customer number accepted. Please proceed to order menu.\n");
      return custNo;
    }
    This is set up just to test the output of the getCustomer function at the moment, and yet when I enter 1 as my customer number, the function returns a 2... what am I doing wrong?

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Replace line 12 with this
    Code:
    printf("Customer number: %d\n", getCustomer(custNo));
    You need to call the function!!! You forgot to. Welcome to the forum!

    EDIT: Not really. You did call her, but you did not collect the return value in main.
    So either do what I said above, or collect the return value at main like this
    Code:
    custNo = getCustomer(custNo);
      printf("Customer number: %d\n", custNo);
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You don't quite have the concept functions of down yet. When you pass "custNo" to the function in that fashion, it does not get updated in "main()" (passing an argument like that makes a copy of that variable local to the function).

    To correct this problem, follow these steps:

    1. Create a local variable in the "getCustomer()" function for reading the input
    2. Return that variable from the function
    3. In "main()", set "custNo" equal to the result of the function (custNo = getCustomer())

    Also, you don't need the newline (\n) in the "scanf()".

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > return custNo;
    Where does this go

    > getCustomer(custNo);
    when you get back to here?

    > scanf("%d\n", &custNo);
    You should remove the \n from the format string, it doesn't do quite what you expect.
    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.

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    Yeah, I definitely don't have the whole function idea quite under wraps yet, I've just made the jump from pseudocode and flowcharts to actually programming in C, and I have never been more confused more often in my life.

    I've taken your input and updated my program and lo and behold, it works! So essentially whenever I want a function to return a value to main(), I have to make a variable in main() and return a value to it using something like variable = functionCall(variable to be returned)?

    Sorry, this is the first legitimate program I've ever tried to write, I'm just a little uncertain about things :P

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Actually, you can do this.
    Code:
    #include <stdio.h>
    
    int getCustomer(void);
    
    int main(void)
    {
      int custNo;
    
      custNo = getCustomer();
      printf("Customer number: %d\n", custNo);
    }
    
    int getCustomer(void)
    {
      int custNo;
      printf("Enter the customer number (0 to quit):\n");
      scanf("%d",&custNo);
      while(custNo<0)
      {
          printf("Invalid customer number, please re-enter.");
          scanf("%d", &custNo);
      }
      printf("Customer number accepted. Please proceed to order menu.\n");
      return custNo;
    }
    Or you could do this
    Code:
    #include <stdio.h>
    
    void getCustomer(int *custNo);
    
    int main(void)
    {
      int custNo;
    
      getCustomer(&custNo);
      printf("Customer number: %d\n", custNo);
    }
    
    void getCustomer(int *custNo)
    {
      printf("Enter the customer number (0 to quit):\n");
      scanf("%d",custNo);
      while(custNo<0)
      {
          printf("Invalid customer number, please re-enter.");
          scanf("%d", custNo);
      }
      printf("Customer number accepted. Please proceed to order menu.\n");
    }
    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.

  7. #7
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    Hey guys,
    Thanks for the help so far, I've been working on it and now I have a different (although possibly related) problem:

    When the showMenu function runs, it appears to only take the user input value for the "option" variable on the first time that it runs.
    Therefore, once the user has entered their customer number, the program will take the first input in the showMenu function and apply it to option, but after that it will proceed in order down the case list for the switch(option). At that point, to add insult to injury, the customer number is showing up wrong.

    Here's my updated code:
    Code:
    #include <stdio.h>
    
    int getCustomer();
    void flushKeyboard(void);
    float custOrder(int custNo, float ttlArt, float ttlBeet, float ttlCar, float ttlOrd);
    float calcDiscount(float costO);
    char showMenu(int custNo);
    float getWeight();
    float calcShipping(float shipWeight);
    
    
    int main(void)
    {
      int custNo;
      float ttlArt, ttlBeet, ttlCar, ttlOrd;
    
    
      custNo = getCustomer();
      printf("Customer number: %d\n", custNo);
      while(custNo != 0)
      {
          custOrder(custNo, ttlArt, ttlBeet, ttlCar, ttlOrd);
      }
      custNo = getCustomer();
    }
    
    
    
    
    // This function is designed to prompt a user for their customer number.
    
    
    int getCustomer()
    {
      int custNo; // Local Variable
      printf("Enter the customer number (0 to quit):\n");
      scanf("%d",&custNo);
      flushKeyboard();
      while(custNo<0)
      {
        printf("Invalid customer number, please re-enter.");
        scanf("%d", &custNo);
        flushKeyboard();
      }
        return custNo;
    }
    
    
    //This function is where the user enters the quantities and calculates the cost of their order.
    
    
    float custOrder(int custNo, float ttlArt, float ttlBeet, float ttlCar, float ttlOrd)
    {
      float weightA, weightB, weightC, shipCost, shipWeight, discount, w, costA, costB, costC, costO;
      char option;
    
    
      option = showMenu(custNo);
      printf("You chose: %c\n", option);
      while(option!='Q')
      {
        switch(option)
        {
          case ('A'):
            {
              printf("Enter the weight of artichokes ordered:\n");
    	      w = getWeight();
       	      weightA = weightA + w;
    	      ttlArt = ttlArt + w;
    	      option = showMenu(custNo);
            }
          case ('B'):
            {
              printf("Enter the weight of beets ordered:\n");
    	      w = getWeight();
    	      weightB = weightB + w;
    	      ttlBeet = ttlBeet + w;
    	      option = showMenu(custNo);
            }
          case ('C'):
            {
              printf("Enter the weight of carrots ordered:\n");
    	      w = getWeight();
    	      weightC = weightC + w;
    	      ttlCar = ttlCar + w;
    	      option = showMenu(custNo);
            }
             case ('Q'):
            {
              return;
            }
          default:
            printf("Invalid Option.\n");option = showMenu(custNo);
            option = showMenu(custNo);
        }
        option = showMenu(custNo);
        printf("You chose: %c\n", option);
      }
      costA = weightA * 1.25;
      costB = weightB * 0.65;
      costC = weightC * 0.89;
      costO = costA + costB + costC;
      discount = calcDiscount(costO);
      costO = costO - discount;
      shipWeight = weightA + weightB + weightC;
      shipCost = calcShipping(shipWeight);
      costO = costO + shipCost;
      printf("===============================================\n");
      printf("CUSTOMER NUMBER: %d\n");
      printf("ITEM         COST/KG       ORDERED         COST\n");
      printf("===============================================\n");
      if(costA>0)
      {
        printf("Artichokes  1.25/kg       %.2f kg        $ %.2f\n", weightA, costA);
      }
      if(costB > 0)
        printf("Beets       0.65/kg       %.2f kg        $ %.2f\n", weightB, costB);
      if(costC > 0)
        printf("Carrots     0.89/kg       %.2f kg        $ %.2f\n", weightC, costC);
      printf("-----------------------------------------------\n");
      if(discount > 0)
        printf("Discount    : $ %.2f", discount);
      printf("Shipping Weight :  %.2f kg \nShipping Cost   : $%.2f\nTotal Order     : $%.2f\n\n\n", shipWeight, shipCost, costO);
    ttlOrd = ttlOrd + costO;
    }
    
    
    // This function calculates the discount (if any).
    float calcDiscount(float costO)
    {
      float discount;
      discount = 0;
      if(costO > 100.00)
        discount = costO *0.05;
      return discount;
    }
    
    
    // This function gets the weight of an order (in kg) from the user.
    float getWeight()
    {
      float w; // local Variable
      scanf("%f", &w);
      while(w<0)
      {
        printf("Invalid Weight, please re-enter.\n");
        scanf("%f", &w);
      }
      return w;
    }
    
    
    // This function displays a menu to the user asking them to select an item to order or exit the program.
    char showMenu(int custNo)
    {
        char option;
        printf("A - Enter weight of artichokes\n");
        printf("B - Enter weight of beets\n");
        printf("C - Enter weight of carrots\n");
        printf("Q - Exit the ordering process for customer %d\n", custNo);
        printf("Enter option:\n");
        scanf("%c", &option);
        option = toupper(option);
        while(option!='A' && option!='B' && option!='C' && option!='Q')
        {
            printf("Invalid option, please re-enter.\n");
            scanf("%c", &option);
            option = toupper(option);
            printf("You chose: %c <-still in showMenu\n", option);
        }
        return option;
    }
    
    
    //This function calculates the shipping cost of the order.
    float calcShipping(float shipWeight)
    {
    
    
      float shipCost;
      shipCost = 0.00;
      if(shipWeight>20.0)
        shipCost = 8.00 + (0.1 * shipWeight);
      if(shipWeight>5.0)
        shipCost = 10.00;
      if(shipWeight>0.0)
        shipCost = 3.50;
      return shipCost;
    }
    
    
    //This module flushes the keyboard buffer to allow the user to enter multiple consecutive values into a scanf statement.
    
    
    void flushKeyboard(void)
    {
      int ch;  // Dummy variable to read data into.
    
    
      while((ch = getc(stdin)) != EOF && ch != '\n');
    }
    Example of the program's current output:
    scanf help, returning incorrect value-2dc8mcx-jpg

    I'm not sure what I'm doing wrong here D:

  8. #8
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Well neither do I.. :P You have to provide us with the updated code, don't you?
    Code - functions and small libraries I use


    It’s 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " —Harold Abelson

  9. #9
    Registered User
    Join Date
    Mar 2013
    Posts
    4
    I've gotten it working to the point where everything is functional (except the final summary), but it still gives an invalid option message after I enter the weight of each item.

    Code:
    #include <stdio.h>
    int getCustomer();
    void flushKeyboard(void);
    float custOrder(int custNo, float ttlArt, float ttlBeet, float ttlCar, float ttlOrd);
    float calcDiscount(float costO);
    char showMenu(int custNo);
    float getWeight();
    float calcShipping(float shipWeight);
    
    int main(void)
    {
    int custNo;
    float ttlArt, ttlBeet, ttlCar, ttlOrd;
    
    custNo = getCustomer();
    printf("Customer number: %d\n", custNo);
    while(custNo != 0)
    {
    custOrder(custNo, ttlArt, ttlBeet, ttlCar, ttlOrd);
    }
    custNo = getCustomer();
    }
    
    
    // This function is designed to prompt a user for their customer number.
    
    int getCustomer()
    {
    int custNo; // Local Variable
    printf("Enter the customer number (0 to quit):\n");
    scanf("%d",&custNo);
    flushKeyboard();
    while(custNo<0)
    {
    printf("Invalid customer number, please re-enter.");
    scanf("%d", &custNo);
    flushKeyboard();
    }
    return custNo;
    }
    
    //This function is where the user enters the quantities and calculates the cost of their order.
    
    float custOrder(int custNo, float ttlArt, float ttlBeet, float ttlCar, float ttlOrd)
    {
    float weightA, weightB, weightC, shipCost, shipWeight, discount, w, costA, costB, costC, costO;
    char option;
    
    option = showMenu(custNo);
    printf("You chose: %c\n", option);
    while(option!='Q')
    {
    switch(option)
    {
    case ('A'):
    {
    printf("Enter the weight of artichokes ordered:\n");
         w = getWeight();
         weightA = weightA + w;
         ttlArt = ttlArt + w;
         break;
    }
    case ('B'):
    {
    printf("Enter the weight of beets ordered:\n");
         w = getWeight();
         weightB = weightB + w;
         ttlBeet = ttlBeet + w;
         break;
    }
    case ('C'):
    {
    printf("Enter the weight of carrots ordered:\n");
         w = getWeight();
         weightC = weightC + w;
         ttlCar = ttlCar + w;
         break;
    }
    case ('Q'):
    {
    break;
    }
    default:
    printf("Invalid Option.\n");option = showMenu(custNo);
    option = showMenu(custNo);
    }
    option = showMenu(custNo);
    printf("You chose: %c\n", option);
    }
    costA = 0;
    costB = 0;
    costC = 0;
    weightA = 0;
    weightB = 0;
    weightC = 0;
    cost0 = 0;
    discount = 0;
    costA = weightA * 1.25;
    costB = weightB * 0.65;
    costC = weightC * 0.89;
    costO = costA + costB + costC;
    discount = calcDiscount(costO);
    costO = costO - discount;
    shipWeight = weightA + weightB + weightC;
    shipCost = calcShipping(shipWeight);
    costO = costO + shipCost;
    printf("===============================================\n");
    printf("CUSTOMER NUMBER: %d\n", custNo);
    printf("ITEM COST/KG ORDERED COST\n");
    printf("===============================================\n");
    if(costA>0)
    {
    printf("Artichokes 1.25/kg %.2f kg $ %.2f\n", weightA, costA);
    }
    if(costB > 0)
    printf("Beets 0.65/kg %.2f kg $ %.2f\n", weightB, costB);
    if(costC > 0)
    printf("Carrots 0.89/kg %.2f kg $ %.2f\n", weightC, costC);
    printf("-----------------------------------------------\n");
    if(discount > 0)
    printf("Discount : $ %.2f", discount);
    printf("Shipping Weight : %.2f kg \nShipping Cost : $%.2f\nTotal Order : $%.2f\n\n\n", shipWeight, shipCost, costO);
    ttlOrd = ttlOrd + costO;
    }
    
    // This function calculates the discount (if any).
    float calcDiscount(float costO)
    {
    float discount;
    discount = 0;
    if(costO > 100.00)
    discount = costO *0.05;
    return discount;
    }
    
    // This function gets the weight of an order (in kg) from the user.
    float getWeight()
    {
    float w; // local Variable
    scanf("%f", &w);
    while(w<0)
    {
    printf("Invalid Weight, please re-enter.\n");
    scanf("%f", &w);
    }
    return w;
    }
    
    // This function displays a menu to the user asking them to select an item to order or exit the program.
    char showMenu(int custNo)
    {
    char option;
    printf("A - Enter weight of artichokes\n");
    printf("B - Enter weight of beets\n");
    printf("C - Enter weight of carrots\n");
    printf("Q - Exit the ordering process for customer %d\n", custNo);
    printf("Enter option:\n");
    void flushKeyboard(void);
    scanf("%c", &option);
    void flushKeyboard(void);
    option = toupper(option);
    while(option!='A' && option!='B' && option!='C' && option!='Q')
    {
    printf("Invalid option, please re-enter.\n");
    scanf("%c", &option);
    option = toupper(option);
    }
    return option;
    }
    
    //This function calculates the shipping cost of the order.
    float calcShipping(float shipWeight)
    {
    
    float shipCost;
    shipCost = 0.00;
    if(shipWeight>20.0)
    shipCost = 8.00 + (0.1 * shipWeight);
    if(shipWeight>5.0)
    shipCost = 10.00;
    if(shipWeight>0.0)
    shipCost = 3.50;
    return shipCost;
    }
    
    //This module flushes the keyboard buffer to allow the user to enter multiple consecutive values into a scanf statement.
    
    void flushKeyboard(void)
    {
    int ch; // Dummy variable to read data into.
    
    while((ch = getc(stdin)) != EOF && ch != '\n');
    }
    
    
    Sample output:
    scanf help, returning incorrect value-21evjbd-jpg

  10. #10
    Registered User
    Join Date
    Nov 2008
    Location
    Phoenix
    Posts
    70
    You're using flush keyboard after getting a char option from the user, but not after getting the weight. When you enter the weight, \n is still in the input buffer. Adding the keyboard flush after getting each weight fixes that.

    Also, in your showMenu option you have this:

    Code:
         printf("Enter option:\n");
         void flushKeyboard(void);
         scanf("%c", &option);
         void flushKeyboard(void);
         option = toupper(option);
    You are actually re-declaring the flushKeyboard function twice. I think you meant to actually use the function. Although with that first call after the printf it is possible that it'll try clearing the input buffer when it might actually be empty at that moment.
    Last edited by Sorin; 03-09-2013 at 01:50 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning an integer ... not returning; weird error
    By Imanuel in forum C++ Programming
    Replies: 19
    Last Post: 09-25-2011, 01:30 PM
  2. Value is incorrect??
    By Myca in forum C Programming
    Replies: 3
    Last Post: 02-11-2011, 10:20 AM
  3. Recursion: base case returning 1, function returning 0
    By yougene in forum C Programming
    Replies: 5
    Last Post: 09-07-2007, 05:38 PM
  4. Function returning incorrect value
    By CHurst in forum C Programming
    Replies: 3
    Last Post: 12-13-2005, 01:27 PM
  5. incorrect output
    By linuxman in forum C Programming
    Replies: 4
    Last Post: 01-03-2004, 08:01 AM

Tags for this Thread