erroneous output while using switch() with a char from vector string

#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> v = {"a", "a", "a"};
    for(int i = 0; i < 3; i++) {
        switch(v[i][0]) {
            case 'a':
                cout<<"case a"<<"\n";
            case 'b':
                cout<<"case b"<<"\n";
            case 'c':
                cout<<"case c"<<"\n";

        }

    }
}

Output:

C:\Users\Administrator\calc>g++ test.cpp && a.exe

case a
case b
case c
case a
case b
case c
case a
case b
case c

Expected output:

case a

why is ‘a’ which is what v[i][0] would always be trigger all the three cases, I don’t understand, isn’t v[i][0] a char ?

>Solution :

You need to use "break" statement in each case.

switch(v[i][0]) {
            case 'a':
                cout<<"case a"<<"\n";
                break;
            case 'b':
                cout<<"case b"<<"\n";
                break;
            case 'c':
                cout<<"case c"<<"\n";
                break;
        }

Leave a Reply