I want to call the function nameOnFile(); to enter a name of a file. The returned string is sent to read(); to load the file and check it. If the file does not exist, I want to give the user the opportunity to start again.
First attempt works. But the second error, the program jumps back to main.
*This is what happends....
Whats is the name of the file? wrongFile
The file coulde note be opend
Do you want to try again? j/n j
Whats is the name of the file? wrongFileAgain
Do you want to try again? j/n j
Do you want to test the program again? j/n
*End
The last string is from main. Should not the program go back to the nameOneFile() function?
How can I solve the problem?
int main(){
string receivedFilename, receivedString;
char x;
do{
receivedFilename = nameOnFile();
receivedString = read(receivedFilename);
cout << "\nDo you want to test the program again? j/n " << endl;
cin >> x;
cin.ignore(10000,'\n');
}while(x == 'j' || x == 'J');
}
string nameOnFile(){
string nameOnFileTxt;
cout << "What is the name of the file?";
getline(cin, nameOnFileTxt);
if(nameOnFileTxt.rfind(".txt") > nameOnFileTxt.length()){
nameOnFileTxt.append(".txt");
}
return nameOnFileTxt;
}
string read(string theFileNamn){
ifstream fin(theFileNamn.c_str());
string fileAsString, words;
char x;
if ( !fin ){
cout << "The file could not be opened" << endl;
cout << "Do you want to try again? j/n" << endl;
cin >> x;
cin.ignore(10000,'\n');
if(x == 'j' || x == 'J'){
nameOnFile();
}
else{
exit( EXIT_FAILURE );
}
}
else{
while(getline(fin, words)){
fileAsString.append(words);
}
return fileAsString;
}
}