I tried to print the things in a vector, but a switch statement is not working

Viewed 43
#include <iostream>
#include <vector>
using namespace std;

void printing(vector<int> numbers);
char ask(char selection);

int main(){
    vector<int> numbers{1,1,2};
    char selection{};
    ask(selection);

    switch(selection) { 
      case 'P':
        printing(numbers);
        break;
      case 'M':
        cout << "FF" << endl;
        break;
      default :
        cout << "error" << endl;
    }
    printing(numbers);
    return 0;
}
    
char ask(char selection)
{        
    cout << "Enter the selection " << endl;
    cout << "\nP - Print numbers" << endl;
    cout << "A - Add a number" << endl;
    cout << "M - Display mean of the numbers" << endl;
    cout << "S - Display the smallest number" << endl;
    cout << "L - Display the largest number"<< endl;
    cout << "Q - Quit" << endl;
    cout << "\nEnter your selection: ";
    cin  >> selection;
    return selection;
}
    
void printing(vector<int> numbers){
        
    if (numbers.size() == 0){
        cout << "[] - the list is empty" << endl;
    }
    else{
        cout << "[ " ;
        for (auto num : numbers){ cout << num << " " ; }
        cout << "] " << endl;
    }
}

Here the switch statement is not working, it's not printing the vector that I need.

1 Answers

You have declared your function char ask(char selection) to take selection by value. Meaning the calling function passes a copy of the char to the ask() function. Any changes to the copy will only be seen in the ask() function and not the function that calls it.

char ask(char selection)
{        
    cout << "Enter the selection " << endl;
    cout << "\nP - Print numbers" << endl;
    cout << "A - Add a number" << endl;
    cout << "M - Display mean of the numbers" << endl;
    cout << "S - Display the smallest number" << endl;
    cout << "L - Display the largest number"<< endl;
    cout << "Q - Quit" << endl;
    cout << "\nEnter your selection: ";
    cin  >> selection;
    return selection;
}

This passing by value is odd since you don't use the value passed into the function and instead want the value from the function. One way to fix this is to change the function to not take a char.

char ask()
{        
    char selection;
    cout << "Enter the selection " << endl;
    cout << "\nP - Print numbers" << endl;
    cout << "A - Add a number" << endl;
    cout << "M - Display mean of the numbers" << endl;
    cout << "S - Display the smallest number" << endl;
    cout << "L - Display the largest number"<< endl;
    cout << "Q - Quit" << endl;
    cout << "\nEnter your selection: ";
    cin  >> selection;
    return selection;
}

then in your calling function int main() use the value returned:

   char selection{ask()};

instead of:

   char selection{};
   ask(selection);

For more information about pass by value see this question: What's the difference between passing by reference vs. passing by value?

Related