【问题标题】:trying to declare a variable local to a function, but get scope error试图声明一个函数本地的变量,但得到范围错误
【发布时间】:2017-12-09 22:21:57
【问题描述】:

这是我的代码的一个小sn-p。您在此处看到的 sn-p 的目的有两个:1)呈现一个菜单——即 menu() 函数,以及 2) 提示用户进行选择并存储它—— selection()。

selection() 从第 18 行开始。

我正在尝试声明一些变量,这些变量将是我的 menu() 和 selection() 函数的本地变量,但是对于我尝试声明的所有内容,我都会遇到这样的错误:

警告:未使用的变量“s”(它为我所有的“char”变量提供了这个) 要么 错误:'snack_selection' 没有在这个范围内声明(它给了我试图声明的两个 'int' 变量)

但这怎么可能呢?我不知道我错过了什么。

感谢患者的反馈。

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
}

此处删除了表面信息的完整代码:

#include <iostream>
#include <iomanip>
#include <cctype>
using namespace std;

//Variable Declarations

int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global

//Function Declarations: 

int menu(void);
// presents menu

int selection(void);
//prompts user to make selection and stores it

int accept_money(int price);
//tells user what money it accepts and the label for each type
//1. repeats back what cost is
//2. tells what  has been paid
//3. allows user to input money by payment selection here

int compute_change(int total_paid, int total_price);
//1.  tells user what total amt was paid
//2.  computes change
//3.  tells user what change will be
//4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)

int main()
{
    cout << "Welcome to the snack vending machine" << endl << endl;

    menu();
    accept_money(price);
    compute_change(total_paid, total_price);

    return 0;
}

//Function Definitions

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 switch case statement (can't be inside function, needs to be global

    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
}


int accept_money(int price)
{
    int nickel = 5, quarter = 25, dollar = 100;
    char money_selection = 0; //condition for money_selection switch case statement
    char n, q, d; //the char variables needed for the money_selection switch case statement

    cout << "Money accepted by the machine:\n"
        << "     " << setw(5) << "N - Nickel" << endl
        << "     " << setw(5) << "Q - Quarter" << endl
        << "     " << setw(5) << "D - Dollar" << endl << endl;

    do
    {
        cout << "Your selected snack item cost: " << price << " CENTS" << endl
            << "Your total inserted: " << total_paid << " CENTS" << endl
            << "Insert amount (enter letter of choice): ";
        cin >> money_selection;
        cout << endl;
        switch ( std::tolower(money_selection) )
        {
        case 'n': total_paid = nickel + total_paid;
            cout << endl;
            break;
        case 'q': total_paid = quarter + total_paid;
            cout << endl;
            break;
        case 'd': total_paid = dollar + total_paid;
            cout << endl;
            break;
        default:
            cout << money_selection << " is not recognized as a coin." << endl << endl;
        }
    } while ( total_paid < price );
    return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
}

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    char y;

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
        << "Dispensing change: " << change << setw(5) << " CENTS" << endl
        << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch ( std::tolower(continue_purchase) )
    {
    case 'y': total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

【问题讨论】:

  • 您显示的代码从不声明名为d 的变量,无论是否未使用。您引用的错误消息似乎与您未显示的某些代码有关。
  • 你从未声明过price ?
  • 在menu()之前添加selection()的原型或在menu()之前移动selection()的定义。
  • char P, S, T, C, B, N; 没有使用这些变量。这些是char 类型的变量,命名为P、S 等...与文字char 值'P'、'S' 等明显不同...删除此行将消除一些警告关于未使用的变量。
  • 您需要发布完整源(这包括任何#include指令)和错误消息的完整文本完全一样它们出现在您的屏幕上。使用edit 链接为您的问题添加必要的信息。

标签: c++ c++11 scope


【解决方案1】:

除了每个人在 cmets 中所说的不使用全局变量和其他良好的编程实践之外,代码本身编译得很好(除非你像我一样在你的编译器标志中使用 -Werror 开关。)但是带有警告。

您似乎误解了,如果您要在 case 语句中使用字符串文字 'P',就像您在函数 int selection(void) 中所做的那样,您必须首先为此声明一个变量 char P .您不必为使用这些字符串文字声明变量。变量 char P 和字符串 'P' 之间没有任何联系。

警告来自以下几行:

在函数int compute_change(int total_paid, int total_price) 中删除以下行:

char y;

然后在函数int accept_money(int price)中删除以下行:

char n, q, d; //the char variables needed for the money_selection switch case statement

最后在函数int selection(void) //FUNCTION: welcomes, presents menu, and prompts user for selection

删除以下行。

char P, S, T, C, B, N;  //the char variables needed for the snack_selection switch case statement (can't be inside function, needs to be global

你会没事的。

如果你真的想使用这些变量,P、S 等等,那么你应该给它们赋值并声明它们是常量。我在这里做了一个案例,给你看。您可以按照类似的方式完成其余的工作。

int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char y = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case y:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

但为了清楚起见,该变量 y 可以被命名为任何名称 - 它不必命名为 y 来存储 'y' 。如果我将该行替换为 const char hakunamatata = 'y'

,则代码会正常工作
int compute_change(int total_paid, int total_price)
{
    char continue_purchase = 0;
    const char hakunamatata = 'y';

    int change = total_paid - price; //has to have somewhere to be stored in this function to work
    int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable

    cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
         << "Dispensing change: " << change << setw(5) << " CENTS" <<
            endl
         << "Would you care to make another purchase (Y/N): ";
    cin >> continue_purchase;

    switch(std::tolower(continue_purchase))
    {
    case hakunamatata:
        total_paid = 0;
        price = 0;
        total_price = 0;
        cout << endl << endl;
        menu();
        break;
    case 'n': cout << "Thank you and enjoy your purchase!";
        break;
    default:
        cout << "Invalid Selection" << endl << endl;
        compute_change(total_paid, total_price);
    }
    return 0;
}

编译器会警告您未使用的变量/参数,因为它揭示了您的疏忽/遗漏等真正错误(例如,在这种情况下,您似乎误解了声明 char 变量需要使用包含的字符串文字与该 char 变量的名称相同的文本)。有关更多信息,请参阅此问题:What are the consequences of ignoring: warning: unused parameter

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    代码编译良好,但包含未使用变量的警告。您在 3 个地方声明了未使用的 char 变量。删除这些声明可以消除警告。在这里我发布了修改后的代码。

    #include <iostream>
    #include <iomanip>
    #include <cctype>
    using namespace std;
    
    //Variable Declarations
    
    int price = 0, total_paid = 0, total_price = 0; //arguments for the three functions in the program.need to be global
    
    //Function Declarations: 
    
    int menu(void);
    // presents menu
    
    int selection(void);
    //prompts user to make selection and stores it
    
    int accept_money(int price);
    //tells user what money it accepts and the label for each type
    //1. repeats back what cost is
    //2. tells what  has been paid
    //3. allows user to input money by payment selection here
    
    int compute_change(int total_paid, int total_price);
    //1.  tells user what total amt was paid
    //2.  computes change
    //3.  tells user what change will be
    //4.  ask user if he or she would like another purchase (if statement. if y, send back to int menu(). if no, thank for purchase message.)
    
    int main()
    {
        cout << "Welcome to the snack vending machine" << endl << endl;
    
        menu();
        accept_money(price);
        compute_change(total_paid, total_price);
    
        return 0;
    }
    
    //Function Definitions
    
    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
    
        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
    }
    
    
    int accept_money(int price)
    {
        int nickel = 5, quarter = 25, dollar = 100;
        char money_selection = 0; //condition for money_selection switch case statement
    
        cout << "Money accepted by the machine:\n"
            << "     " << setw(5) << "N - Nickel" << endl
            << "     " << setw(5) << "Q - Quarter" << endl
            << "     " << setw(5) << "D - Dollar" << endl << endl;
    
        do
        {
            cout << "Your selected snack item cost: " << price << " CENTS" << endl
                << "Your total inserted: " << total_paid << " CENTS" << endl
                << "Insert amount (enter letter of choice): ";
            cin >> money_selection;
            cout << endl;
            switch ( std::tolower(money_selection) )
            {
            case 'n': total_paid = nickel + total_paid;
                cout << endl;
                break;
            case 'q': total_paid = quarter + total_paid;
                cout << endl;
                break;
            case 'd': total_paid = dollar + total_paid;
                cout << endl;
                break;
            default:
                cout << money_selection << " is not recognized as a coin." << endl << endl;
            }
        } while ( total_paid < price );
        return total_paid;  //this function needs to return updated value, or any changes made to it will remain local to the function
    }
    
    int compute_change(int total_paid, int total_price)
    {
        char continue_purchase = 0;
    
        int change = total_paid - price; //has to have somewhere to be stored in this function to work
        int amt_inserted = total_paid; //was not using updated value of total_paid from previous fnction, so had to save it to a variable local to this one from the global variable
    
        cout << "Your total inserted: " << amt_inserted << " CENTS" << endl
            << "Dispensing change: " << change << setw(5) << " CENTS" << endl
            << "Would you care to make another purchase (Y/N): ";
        cin >> continue_purchase;
    
        switch ( std::tolower(continue_purchase) )
        {
        case 'y': total_paid = 0;
            price = 0;
            total_price = 0;
            cout << endl << endl;
            menu();
            break;
        case 'n': cout << "Thank you and enjoy your purchase!";
            break;
        default:
            cout << "Invalid Selection" << endl << endl;
            compute_change(total_paid, total_price);
        }
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2020-07-31
      相关资源
      最近更新 更多