Thanks for looking at my question in advanced. It may be quite a simple one!
I have a menu where the user can select which file they wish to run through the system.
The code below is what my menu options do:
int menuLoop = 1;
int userChoice;
std::string getInput;
while(menuLoop == 1)
{
std::cout << "Menu\n\n"
<< "1. 20 names\n"
<< "2. 100 names\n"
<< "3. 500 names\n"
<< "4. 1000 names\n"
<< "5. 10,000 names\n"
<< "6. 50,000 names\n\n";
std::cin >> userChoice;
std::string getContent;
if(userChoice == 1)
{
std::cout << "\n20 names\n";
std::ifstream openFile("20.txt");
}
else if(userChoice == 2)
{
std::cout << "\n100 names\n";
std::ifstream openFile("1C.txt");
}
else if(userChoice == 3)
{
std::cout << "\n500 names\n";
std::ifstream openFile("5C.txt");
}
else if(userChoice == 4)
{
std::cout << "\n1000 names\n";
std::ifstream openFile("1K.txt");
}
else if(userChoice == 5)
{
std::cout << "\n10,000 names\n";
std::ifstream openFile("10K.txt");
}
else if(userChoice == 6)
{
std::cout << "\n50,000 names\n";
std::ifstream openFile("50K.txt");
}
The code that follows in the while loop deals with the values that are in the selected file, but the code is the same for each option. The next line is:
if(openFile.is_open())
Because of the way I have done it, it is saying “openFile” is undefined, which I completely understand but I was wondering whether anyone knows how I could get around?
Declare
openFilejust once earlier in thewhileloop like so:This gives you an
std::ifstreamthat is not associated with any particular file. Then in each of yourifstatements usestd::ifstream::openrather than thestd::ifstreamconstructor:Of course, make sure each one has the correct file name.
This way, the
openFileobject’s scope will be thewhileloop but you can open a different file depending on your condition.