0

i"m new at this.. please help me! i keep getting this error Error 5 error C2360: initialization of 'levelOne' is skipped by 'case' label.
I get a "transfer of control bypasses initialization of:" error when i try to build the following switch:

void ViewCourses() {

    int choice = 0;
    cout<<"Please select your level:"<<endl;
    cout<<"1) level one"<<endl;
    cout<<"2) level two"<<endl;
    cout<<"3) level three"<<endl;
    cout<<"4) level four"<<endl;
    cout<<"5) level five"<<endl;

    cout<<"Please enter Level: ";
    cin >> choice;

            switch(choice)
            {

            case 1: ifstream levelOne;
                    levelOne.open("level1.txt");
                    break;

            case 2: ifstream levelTwo;
                    levelTwo.open("level2.txt");
                    break;

            case 3: ifstream levelThree;
                    levelThree.open("level3.txt");
                    break;

            case 4: ifstream levelFour;
                    levelFour.open("level4.txt");
                    break;

            case 5: ifstream levelFive;
                    levelFive.open("level5.txt");
                    break;

            default:    cout << "Invalid option please try again" << endl;//when an incorrect option is entered
                        break;
            }
}

Edited by babiiros

2
Contributors
1
Reply
8
Views
3 Years
Discussion Span
Last Post by Ancient Dragon
1

objects can't be declared in case statements without { and }, for example:

switch(choice)
            {
            case 1:
            {
                ifstream levelOne;
                    levelOne.open("level1.txt");
            }
            break;

That also means that the stream will be closed as soon as the break statement is executed and the switch is exited. I think you need to rethink what you are doing here and devise a different solution. You would just declare one fstream object before the switch then use it to open the correct file

ifstream in;
switch(choice)
            {
            case 1:
                    in.open("level1.txt");
                    break;
            case 2: 
                    in.open("level2.txt");
                    break;
            case 3: 
                    in.open("level3.txt");
                    break;
            case 4: 
                    in.open("level4.txt");
                    break;
            case 5: 
                    in.open("level5.txt");
                    break;
            default:    cout << "Invalid option please try again" << endl;//when an incorrect option 
Votes + Comments
I was just about to suggest the same thing! You beat me to it! :)
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.