int main ()
{
//FILLING DATA ARRAYS
// ask user for dat file
start:
cout << "Input filename where the raw data exist-->";
char filename [50];
ifstream dat;
cin.getline(filename,50);
dat.open(filename);
// if file isnt there report error
if (!dat.is_open()){
cout << "File Does Not Exist!" << endl ;
goto start;
}
// more code after this that fills arrays from a file
the person that I am writing the code for doesn't like the goto statement is there any other option?
In this case, you are using the goto statement to loop back and begin a new iteration. You have many options when it comes to loops including while, for, for-each, and do/while.
For example:
ifstream dat;
do {
cout << "Input filename where the raw data exist-->";
char filename [50];
cin.getline(filename,50);
dat.open(filename);
if (!dat.is_open())
cout << "File Does Not Exist!" << endl ;
} while (!dat.is_open());
EDIT: if you dislike two open checks: Warning: esoteric technique. Do not use in real projects
} while(!dat.is_open() && (cout << "File Does Not Exist!" << endl, true));
> the person that I am writing the code for doesn't like the goto statement is there any other option?
Why does this person not like a goto statement?
He has read somewhere (mindlessly): 'just don't ever use goto, and you are on velvet'. Just disguise the very same goto as a while or do-while loop and he won't even know that he has been conned.
He knows that the program structure can be improved. Then you would have to do some actual work. For instance, if you have a conforming library implementation (one with moveable streams, for instance Microsoft):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
std::ifstream file_from_user_input()
{
std::cout << "Input filename where the raw data exist-->";
std::string file_name ;
std::getline( std::cin, file_name ) ;
return std::ifstream(file_name) ;
}
int main ()
{
std::ifstream file ;
while( ! ( file = file_from_user_input() ) ) std::cerr << "error opening file\n" ;
// use the stream
}
Note: If you go the while or do-while way, make sure that the stream object is programmatically visible and alive after you have opened it.
In that case it is.
However there could be some cases when use of goto is justified. It is not always hampers readability. Sometimes it actually improves it.
For example if you need to break out from multiple nested loops.
But you should always think before use it: "can I refactor my program to not use goto here and to not lose readability or effeciency".