C ++ Возможная проблема с областью действия в функции quit () - PullRequest
0 голосов
/ 24 февраля 2020

Попытка объявить и инициализировать выбор, чтобы он имел другое значение, отличное от 'Q', и возвращал это значение, так что продолжайте, пока l oop продолжит работать. Я не могу изменить значение переменной выбора изнутри функции с именем quit (). переменная выбора определяется в функции get_selection (). Я все еще очень плохо знаком с программированием и C ++, кто-нибудь может мне помочь с этим? Я не знаю, как изменить значение выбора, чтобы сохранить выполнение, пока l oop работает, когда кто-то вводит 'q' или 'Q', чтобы выйти из l oop. Исходный код ниже. Это мой первый вопрос переполнения стека. Пожалуйста, дайте конструктивную обратную связь, если я задал этот вопрос плохо, чтобы я учился на нем и делал лучше в следующий раз. Большое спасибо за ваше время и надеюсь, что у вас есть благословенный день.

#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; 
}

1 Ответ

0 голосов
/ 24 февраля 2020

Вы возвращаете значение из функции quit, но не сохраняете его и не воздействуете на него в функции main.

Вероятно, не возвращает значение из функции quit, и при этом он не должен отображать меню или получать выбор, как это делается в функции main. Вместо этого я бы предложил что-то вроде

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";
    }
}
...