mercredi 5 juillet 2017

trying to declare a variable local to a function, but get scope error

Here's a small snippet of my code. The purpose of the snippet you see here is twofold 1)present a menu -- that's the menu() function, and 2) prompt the user to make a selection and store it -- selection().

selection() starts on line 18.

I'm trying to declare some variables that will be local to my menu() and selection() functions, but I get errors like this, for everything I try to declare:

warning: unused variable 'd' (it gave this for all my 'char' variables) or error: 'snack_selection' was not declared in this scope (it gave this for the two 'int' variables I tried to declare)

but how can that be? I don't know what I'm missing.

patient feedback is appreciated.

int menu(void)
{  
cout << "Available snacks to select from: " << endl  //presents menu
      << "     " << setw(5) << "P - Potato Chips" << setw(9) << "$1.25" 
<< endl  //prompts user to make a selection (until it is valid)
      << "     " << setw(5) << "S - Snickers Bar" << setw(9) << "$1.35" 
<< endl
      << "     " << setw(5) << "T - Pop Tart" << setw(13) << "$0.95" << 
endl
      << "     " << setw(5) << "C - Cookies" << setw(14) << "$1.50" << 
endl
      << "     " << setw(5) << "B - Brownie" << setw(14) << "$1.75" << endl
      << "     " << setw(5) << "N - Nuts" << setw(17) << "$1.40" << endl;
  selection();
return 0;
}

int selection(void)   //FUNCTION: welcomes, presents menu, and prompts user for selection
{

int potato_chip_price = 125, snickers_bar_price = 135, pop_tart_price = 95, cookies_price = 150, brownie_price = 175, nuts_price = 140;
char snack_selection = 0; //condition for snack_selection switch case statement
char P, S, T, C, B, N;  //the char variables needed for the snack_selection 


cout << "Please enter the letter labeling your snack selection: ";
cin >> snack_selection;
cout << endl;

  switch(std::toupper(snack_selection))  
    { //beginning of switch statement (goes through all the "legal" options so there is an "illegal" option
    case 'P': price = potato_chip_price; //setting it up this way stores the value of price with the value of potato_chip_price. if the other way around, pop_tart_price would become 0 since that is what price is set to.
        break;
    case 'S': price = snickers_bar_price; //stores the snack selection price in CENTS to the int price variable needed for the next function's argument
        break;
    case 'T': price = pop_tart_price;
        break;
    case 'C': price = cookies_price;
        break;
    case 'B': price = brownie_price;
        break;
    case 'N': price = nuts_price;
        break;
    default:
    cout << "Invalid selection!";
            menu();
    } //end of switch statement
return(price); //needs to return some kind of value bc it isn't a void function, and compiler will give a warning
}

Aucun commentaire:

Enregistrer un commentaire