简体   繁体   中英

C++ Possible scope issue in the quit() function

Tried declaring and initializing selection to have another value other than 'Q' and returning that value so that do while loop would keep running. I can't seem to change the value of the selection variable from inside of a function named quit(). the selection variable is defined within the get_selection() function. I am still very new to coding and C++ can somebody help me with this? I don't know how to change the value of selection to keep the do while loop running once someone enters 'q' or 'Q' to quit the loop. The source code is below. This is my first stack overflow question. Please give constructive feedback if i have asked this question in a bad way so that I learn from it and do better next time. Thank you so much for your time and hope you have a blessed day.

#include <iostream>
#include <vector>

using namespace std;

// Function Prototypes
void display_menu();
char get_selection();
void print_numbers(const vector<int> &list);
void add_number(vector<int> &list);
void remove_number(vector<int> &list);
void display_mean(const vector<int> &list);
void smallest_number(const vector<int> &list);
void largest_number(const vector<int> &list);
char quit();
void handle_unknown();
// End of Function Prototypes

void display_menu() {
    cout << "-------------------------------------------\n";
    cout << "Please select one of the following choices:|\n ";
    cout << "P - Print Numbers                         |\n ";
    cout << "A - Add a Number                          |\n ";
    cout << "R - Remove a Number                       |\n";
    cout << " M - Display Mean of the Numbers           |\n ";
    cout << "S - Display the Smallest Number           |\n ";
    cout << "L - Display the Largest Number            |\n ";
    cout << "Q - Quit                                  |\n ";
    cout << "-------------------------------------------\n";
    cout << "\nEnter Selection Here: ";
}

char get_selection() {
    char selection {};
    cin >> selection;
    return toupper(selection);
}

void print_numbers(const vector<int> &list) {
     // if the User selects P it will display the list within brackets
    cout << "\n============================================\n"; 
    cout << "\n[ ";
    for ( auto index : list) {
        cout<< index << " ";
    }
    cout << "]";
    cout << "\n\n============================================\n\n";
}

void add_number(vector<int> &list) {
    // if the user selects A it will Add a Number to the list
    int number {};
    cout << "\n==========================================================\n\n";
    cout << "- Please enter a number to be ADDED to the list: ";
    cin >> number;
    list.push_back(number);
    cout << "- The number " << number << " was ADDED to the list\n\n";
    cout << "==========================================================\n\n";
}

void remove_number(vector<int> &list) {
    // if the user selects R it will REMOVE a Number from the list
    char choice {};
    cout << "\n- If you select Yes the last number you added to the list will be REMOVED from the list(Y/N): ";
    cin >> choice;
    if ( (choice == 'Y' || choice == 'y') && list.size() == 0) {
        cout << "- Sorry, but there is currently nothing in the list to remove.\n\n";
        cout << "==========================================================================================================\n\n";
    }
    else if (choice == 'Y' || choice == 'y'){
        list.pop_back();
        cout<< "- The last number you entered was removed from the list\n\n";
        cout << "==========================================================================================================\n\n";
    }
    else if (choice == 'N' || choice == 'n') {
        cout << "- The number survived the purge!!!\n\n";
        cout << "==========================================================================================================\n\n";
    }
    else {
        cout << "- You did not enter a valid response, no action was taken\n\n";
        cout << "==========================================================================================================\n\n";
    }
}

void display_mean(const vector<int> &list) {
    // if the user selects M it will display the mean of the numbers
    cout << "\n===============================================================\n\n";
    int sum {}; //all the integers in the list added together
    double mean {}; // the sum / list.size()
    for ( auto integer : list) {
        sum = sum + integer;
    }
    mean = static_cast<double>(sum) / list.size();
    cout << "- The Sum of all the numbers in the list is: " << sum << endl;
    cout << "- The Mean of all the numbers in the list is: " << mean << endl;
    cout << "\n===============================================================\n";
}

void smallest_number(const vector<int> &list) {
    // Displays the smallest number
    cout << "\n=========================================================\n\n";
    int min = list.at(0);
    for ( auto nums : list ) {
        if ( nums < min) {
            min = nums;
        }
    } 
   cout << "- The Min in the list is: " << min << endl;
   cout << "\n=========================================================\n\n";
}


void largest_number(const vector<int> &list) {
    // Displays the largest number
    cout << "\n=========================================================\n\n";
    int max = list.at(0);
    for ( auto nums : list ) {
        if ( nums > max) {
           max = nums;
        }
    } 
    cout << "- The Max in the list is: " << max << endl;
    cout << "\n=========================================================\n\n";
}

char quit() {
   // Are you sure you want to quit prompt
    char quit_prompt {};
    cout << "\n==============================================\n\n";
    cout << "Are you sure you want to quit (Y/N)? ";
    cin >> quit_prompt;
    if ( quit_prompt == 'Y' || quit_prompt == 'y') {
        cout << "Have a blessed day!!!" << endl;
        cout << "\n==============================================\n\n";
        return 'a';
    }
    else if ( quit_prompt == 'N' || quit_prompt == 'n') {
        cout << "Choose a option\n";
        cout << "\n==============================================\n\n";
        display_menu();
        return get_selection();

    }
    else if ( quit_prompt == 'Q' || quit_prompt == 'q') {
        cout << "Have a blessed day!!!\n";
        cout << "\n==============================================\n\n";
        return 'a';
    }
    else {
        cout << "You entered a invalid response, no action was taken\n";
        cout << "\n==============================================\n\n";
        display_menu();
        return get_selection();
    }
}

void handle_unknown() {
    cout << "Unknown selection - try again" << endl;
}

int main() {

    vector<int> list {1,2,3}; //have to create the list outside of the loop otherwise the loop will 
reset the list every single time the loop resets (lesson learned)
        // user input a character that will get saved to this selection variable
        char selection {};
        // run this loop unless the user inputs 'Q' or 'q'
        do {
        // tells the user to enter a valid choice if they don't
        display_menu();
        selection = get_selection();
        switch (selection) {
            case 'P':
                print_numbers(list);
                break;
            case 'A':
                add_number(list);
                break;
            case 'R':
                remove_number(list);
                break;
            case 'M':
                display_mean(list);
                break;
            case 'L':
                largest_number(list);
                break;
            case 'S':
                smallest_number(list);
                break;
            case 'Q':
                quit();
                break;
            default:
                handle_unknown();
        }
    } while ( selection != 'Q' ); // using the && logical statement because of the != comparison.

    return 0; 
}

You return a value from the quit function, but you don't save it or act upon it in the main function.

You should probably not return a value from the quit function, and neither should it display the menu or get the selection, as it's done in the main function. Instead I would suggest something like

void quit() {
   // Are you sure you want to quit prompt
    char quit_prompt {};
    cout << "\n==============================================\n\n";
    cout << "Are you sure you want to quit (Y/N)? ";
    cin >> quit_prompt;
    if ( quit_prompt == 'Y' || quit_prompt == 'y' ||
         quit_prompt == 'Q' || quit_prompt == 'q') {
        cout << "Have a blessed day!!!" << endl;
        cout << "\n==============================================\n\n";
        exit(0);  // Exit the program
    }
    else if ( quit_prompt == 'N' || quit_prompt == 'n') {
        // Do nothing
    }
    else {
        cout << "You entered a invalid response, no action was taken\n";
        cout << "\n==============================================\n\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM