Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading