Search code examples
c++if-statementfstreamifstreamgoto

How can I use goto to perform a task for a file instead of using a function?


So I've always heard that using goto makes you a terrible person, so I've never really experimented with it until recently. For fun, I decided to make a program that HEAVILY relies on goto statements to see for myself when they can actually come in handy.

In other words, I am purposely trying to stay away from anything generally accepted as good programming, and I'm experimenting with other methods...

That being said, I ran into my first issue. I want to read from a file, and emulate a "function" by simply transferring the data I gathered to another part of my code.. run it through... and return back to the file.

Here is some of my code so you can get the basic idea of what I'm trying to do:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    string command, fileName, fileLine;

    while (command != "quit")
    {
        cout << "cmd> ";
        cin >> command;

        if (command == "function")
        {
            FUNCTION: // I want to manipulate the data I gather from the file here.

            cout << "Perform a certain task here instead of using a function." << endl;

            goto FILE;
        }

        else if (command == "file")
        {
            cout << "filename> ";
            cin >> fileName;

            ifstream myFile(fileName.c_str());

            if (myFile.is_open())
            {
                while (getline(myFile, fileLine))
                {
                    goto FUNCTION;

                    FILE:

                    cout << "You finished your task using the above 'if' statement." << endl;
                }

                myFile.close();
            }
        }

        else if (command == "quit")
            break;

        else
            cout << "Invalid Command." << endl;
    }

    return 0;
}

When I try to compile my code, I get the following errors:

example.cpp: In function ‘int main()’:
example.cpp:37:6: error: jump to label ‘FILE’ [-fpermissive]
example.cpp:21:9: error:   from here [-fpermissive]
example.cpp:29:13: error:   crosses initialization of ‘std::ifstream myFile’

It seems like I can't use goto to jump over the initialization of "ifstream myFile." Does anyone know a way, without using a function and without using any flags, that I can accomplish this task using goto?


Solution

  • I found the solution to my problem.

    Instead of writing:

    ifstream myFile(fileName.c_str());
    

    You should declare the ifstream variable towards the top of main() like so:

    ifstream myFile;
    

    Then, after reading the file name, you should assign it to the input file stream:

    myFile.open(fileName.c_str());
    

    This will allow you use goto to perform a task for a file instead of using a function (without running into the errors I was receiving).