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


so i've heard using goto makes terrible person, i've never experimented until recently. fun, decided make program heavily relies on goto statements see myself when can come in handy.

in other words, purposely trying stay away accepted programming, , i'm experimenting other methods...

that being said, ran first issue. want read file, , emulate "function" transferring data gathered part of code.. run through... , return file.

here of code can basic idea of i'm trying 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: // want manipulate data gather file here.              cout << "perform task here instead of using 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 task using above 'if' statement." << endl;                 }                  myfile.close();             }         }          else if (command == "quit")             break;          else             cout << "invalid command." << endl;     }      return 0; } 

when try compile code, following errors:

example.cpp: in function ‘int main()’: example.cpp:37:6: error: jump label ‘file’ [-fpermissive] example.cpp:21:9: error:   here [-fpermissive] example.cpp:29:13: error:   crosses initialization of ‘std::ifstream myfile’ 

it seems can't use goto jump on initialization of "ifstream myfile." know way, without using function , without using flags, can accomplish task using goto?

the problem compiler tells you... can't skip initialization of ifstream myfile(filename.c_str()); goto statement attempts accomplish. if ignore warning you'd situation might use myfile before allocated/initialized or after freed(which bad). i'd suggest move if (command == "function") code block inside scope of else if (command == "file").

a few general suggestions:

1) goto heavily used in c code cleanup. can browse linux kernel , see plenty of examples 1 2 3

2) goto bad in c , worse in c++, because in c++ have kinds of implicit memory manipulations avoid in c. maybe want rewrite code in c , you'd no error/warning.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -