0

I'm trying to write a program that asks for the flavor of a specific scoop of ice cream and adding it to a total price variable in C. Here's what I have: (Note: Sf and S are int variables, price is a float variable, and F is a char variable)

#include <stdio.h>

void main(void)
{
    float price;
    char F;
    int S;
    int Sf = 1;
    int T = 0;
    
    printf("\nHow many scoops do you want? You can choose 1 to 10 scoops\n");
    scanf("%d", &S);
    printf("\nHere are your flavor options: Vanilla (V) Chocolate (C) Strawberry (S) Oreo (O) Butter Pecan (B)");

    while (Sf <= S)
    {
        printf("\nWhat flavor do you want for scoop %d?\n", Sf);
        scanf(" %c", &F);

        switch (F)
        {
            case 'V':
            {
                price = price + 0.70;
                break;
            }
            case 'C':
            {
                price = price + 0.75;
                break;
            }
            case 'S':
            {
                price = price + 0.80;
                break;
            }
            case 'O':
            {
                price = price + 0.85;
                break;
            }
            case 'B':
            {
                price = price + 0.90;
                break;
            }
            default:
            {

            }
            Sf += 1;
        }
    }
    printf("\n\n%f", price);
}

I don't know what I'm doing wrong, and I'm very new to C. I appreciate any help

Edit: what happens is when I input one of the requested letters, it simply repeats the question until I enter a number. However, it also runs the specific case. this is what I am talking about:

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • 3
    Rather than telling us the type of the different variables, include the variable declarations in the code you've posted. – larsks Mar 25 '23 at 20:52
  • Instead of a `while` loop, I suggest you use a `for` loop instead. At least then you hopefully won't place the increment `Sf+=1` in the wrong place. – Some programmer dude Mar 25 '23 at 20:54
  • 2
    Other than that, what is the problem you have with the code you show us? For some specified input, what is the expected and actual output? Please [edit] your question to tell us. Also please try to create a proper [mre] to show us. – Some programmer dude Mar 25 '23 at 20:55
  • what are `Sf` and `price` initialized to? As mentioned, please edit your question and provide a [mre] – yano Mar 25 '23 at 21:01
  • I suggest you make arrays of prices etc. Hard coding everything is high maintenance. – Weather Vane Mar 25 '23 at 21:03
  • There doesn't appear to be anything wrong with the `switch` statement. Although it does require the user to enter an uppercase letter. To handle uppercase and lowercase choices, add a second case statement to every selection. For example, after the line `case 'V':` add the line `case 'v':`. – user3386109 Mar 25 '23 at 21:07
  • I suggest you define a struct, say, 'struct flavor { const char *name, const char short_name, double price }` and use that to generate both the prompt and the calculation. – Allan Wind Mar 25 '23 at 21:11
  • There is one problem with the `switch` statement: it only increments `sF` when someone makes an invalid choice. This means that the loop will never exit as long as someone makes valid choices. – larsks Mar 25 '23 at 21:11
  • @larsks Thanks so much man! I apologize if my post was hard to read, I'm new to this site. Thanks everyone else for the input! I really appreciate it! – Robert Westmeyer Mar 25 '23 at 21:22

3 Answers3

1

There are multiple problems:

  • price is not initialized, hence the code has undefined behavior and the price will be meaningless if printed at all

  • You only increment Sf += 1; in the default case, ie: if the character typed is not recognised as a flavor.

  • You should test the return values of scanf() to detect invalid or missing input.

Here is a modified version with more explicit variable names:

#include <stdio.h>

int main(void) {
    float price;
    char flavor;
    int total_scoops;
    int scoop;
    
    printf("\nHow many scoops do you want? You can choose 1 to 10 scoops\n");
    if (scanf("%d", &total_scoops) != 1)
        return 1;

    if (total_scoops < 1 || total_scoops > 10) {
        printf("\nCannot serve this request\n");
        return 1;
    }
    printf("\nHere are your flavor options:\n"
           "Vanilla (V) Chocolate (C) Strawberry (S) Oreo (O) Butter Pecan (B)\n");

    price = 0;
    scoop = 0;
    while (scoop < total_scoops) {
        scoop += 1;
        printf("\nWhat flavor do you want for scoop %d?\n", scoop);
        if (scanf(" %c", &flavor) != 1)
            return 1;

        switch (flavor) {
          case 'V':
            price = price + 0.70;
            break;
          case 'C':
            price = price + 0.75;
            break;
          case 'S':
            price = price + 0.80;
            break;
          case 'O':
            price = price + 0.85;
            break;
          case 'B':
            price = price + 0.90;
            break;
          default:
            printf("unknown flavor: %c\n", flavor);
            scoop -= 1;  // same player scoops again
            break;
        }
    }
    printf("\nPrice: %.2f\n", price);
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
1

@chqrlie has answered the question, but I wanted to present this alternative implementation which implements some of the other suggestions that showed up in the comments.

In particular, this defines a list of flavors rather than hardcoding the choices into the switch statement.

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXLINELEN 80

/*
 * Here we define a struct that will hold a flavor name, a menu key for
 * selecting that flavor, and a price.
 */
struct prices {
  char *name;
  char key;
  float price;
};

/*
 * Next, we create a list of prices for our ice cream falvors. We terminate
 * the list with a flag value (in this case a NULL name) so that we can
 * identify the end of the list without needing to know the length of
 * the list in advance.
 */
struct prices flavors[] = {
    {"Vanilla",    'v', 0.70},
    {"Chocolate",  'c', 0.75},
    {"Strawberry", 's', 0.80},
    {"Oreo",       'o', 0.85},
    {NULL, 0, 0.0},
};

int main() {
  int number_of_scoops;
  float price = 0;

  printf("You can choose 1 to 10 scoops.\n");

  // Loop until we receive a valid response.
  while (1) {
    char answer[MAXLINELEN];
    printf("How many scoops do you want? ");

    /*
     * We're using fgets() instead of scanf() here because dealing with
     * invalid input (input that cannot be converted by your format
     * specifiers) can be a little tricky with scanf().
     *
     * See https://stackoverflow.com/a/40552127/147356 for a more
     * in depth discussion on this topic.
     */
    fgets(answer, MAXLINELEN, stdin);

    // strtol() returns zero for non-digit inputs
    number_of_scoops = strtol(answer, NULL, 10);
    if (number_of_scoops > 0 && number_of_scoops <= 10)
      break;
  }

  /*
   * Generate a menu of available options, showing
   * the menu key , the flavor name, and the price.
   */
  printf("You may choose the follow flavors:\n");
  for (int i = 0; flavors[i].name; i++) {
    printf("  [%c] %s (%0.2f)\n", flavors[i].key, flavors[i].name,
           flavors[i].price);
  }
  printf("\n");

  for (int i = 0; i < number_of_scoops; i++) {
    int found = 0;

    // Loop until we receive a valid response.
    while (!found) {
      char answer[MAXLINELEN];
      char flavor;

      printf("Which flavor do you want for scoop %d? ", i + 1);
      fgets(answer, MAXLINELEN, stdin);

      // Allow user to enter either upper or lower case choices.
      flavor = tolower(answer[0]);

      // Scan through list of flavors looking for a match
      for (int j = 0; flavors[j].name; j++) {
        if (flavors[j].key == flavor) {
          found = 1;
          price += flavors[j].price;

          // Provide some feedback about their choice
          printf("  adding %s; price is now %0.2f\n", flavors[j].name, price);
        }
      }
    }
  }

  printf("Total price: %0.2f\n", price);
}
larsks
  • 277,717
  • 41
  • 399
  • 399
0

change your code to this:

#include <stdio.h>

void main(void)
{
    float price = 0.0;
    char F;
    int S;
    int Sf = 1;

    printf("\nHow many scoops do you want? You can choose 1 to 10 scoops\n");
    scanf("%d", &S);
    printf("\nHere are your flavor options: Vanilla (V) Chocolate (C) Strawberry (S) Oreo (O) Butter Pecan (B)");

    while (Sf <= S)
    {
        printf("\nWhat flavor do you want for scoop %d?\n", Sf);
        scanf(" %c", &F);

        switch (F)
        {
            case 'V':
            {
                price = price + 0.70;
                break;
            }
            case 'C':
            {
                price = price + 0.75;
                break;
            }
            case 'S':
            {
                price = price + 0.80;
                break;
            }
            case 'O':
            {
                price = price + 0.85;
                break;
            }
            case 'B':
            {
                price = price + 0.90;
                break;
            }
            default:
            {
                printf("\nInvalid flavor option\n");
                break;
            }
        }
        Sf += 1;
    }
    printf("\n\nTotal price: $%.2f", price);
}
F. Müller
  • 3,969
  • 8
  • 38
  • 49
ChamithX
  • 1
  • 1