I am brand new to trying to learn C++ and have signed up for a class to expand my knowledge in this area. The instructor has never taught a class before and sadly, 16 students have dropped the class. I'm still trying to hang in there but I cannot make sense of some of an assignment. I am determined to figure it out, but I need some help with a piece that I have spent hours trying to get working and cannot.
I want to pass a file stream to case statements in a switch statement and in turn, each case will call a function to do something with the file stream. I can get the file open in the first case, but in the second, if i try to process it, i don't know how to pass the stream / file I captured in the first case. This is what I have so far:
file.open(name, ios::in);
if (file.fail())
return false;
else
return true;
}
void showContents(fstream &file) {
char line[50];
while (file >> line) {
cout << line << endl;
}
}
int DisplayMenu(){
//display the main menu
int item;
//Show user for the name of the data file
cout << endl << endl << endl;
//cout << "Current Data File: " << dataFile << endl << endl;
cout << "***** MAIN MENU *****" << endl << endl;
cout << "(1) Select / create data file (.txt extension will be added automatically)" << endl;
cout << "(2) Display all numbers, total and average" << endl;
cout << "(3) Display all numbers sorted" << endl;
cout << "(4) Search for a number and display how many times it occurs" << endl;
cout << "(5) Display the largest number" << endl;
cout << "(6) Append a random number(s)" << endl;
cout << "(7) Exit the program" << endl;
switch(choice)
{
case 1:
cout << "Enter file name. Do not include extension: ";
cin >> UserEntry;
Filepath=filePrefix;
Filepath.append(UserEntry);
Filepath.append(fileSuffix);
//check if file is found. if not, create it
if (!openFileIn(dataFile,sDataFile))
{
cout << "No file found." << endl;
//CreateFile(sDataFile);
}
else
cout << "file found!" << endl;
showContents(dataFile); //this works
DisplayMenu();
// break;
case 2:
//check if file is open
if (!openFileIn(dataFile,sDataFile))
{
cout << "No file found.." << endl;
//CreateFile(sDataFile);
}
else
showContents(dataFile); //this does not work
DisplayMenu();
break;
case 3:
break;
case 4:
break;
default:
cout << "Invalid selection. Choose a number between 1 and 7." << endl;
break;
}