Why won't this code open the .txt files?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • idkwidlol
    New Member
    • Apr 2016
    • 1

    Why won't this code open the .txt files?

    Code:
    #include <iostream>
    #include <fstream>
    
    using namespace std;
    
    int main()
    
    {
    	cout << "Willkommen zu meinem Programm!\n\n";
    	char choice;
    	do {
    		//User Prompt
    		cout << "Please Choose a Selection from the Menu.\n\n";
    		//Display Menu
    		cout << "1) Program Languages and their uses\n2) Different Programming Paradigms\n3) Different C++ Features and their uses \n4) Exit\n\n";
    		cin >> choice;
    		cout << endl;
    		if (choice == '1')
    		{
    			//Read the file
    			ifstream infile;
    			ofstream outfile;
    			//Open the File
    			infile.open("ProgrammingLanguages.txt", ios::in);
    			//Ensure File exists
    			if (!infile)
    			{
    				cout << "File does not exist!\n\n";
    			}
    			//Close the file
    			infile.close();
    		}
    		if (choice == '2')
    		{
    			//Read the file
    			ifstream infile;
    			ofstream outfile;
    			//Open the File
    			infile.open("ProgrammingParadigms.txt", ios::in);
    			//Ensure File exists
    			if (!infile)
    			{
    				cout << "File does not exist!\n\n";
    			}
    			//Close the file
    			infile.close();
    		}
    		if (choice == '3')
    		{
    			//Read the file
    			ifstream infile;
    			ofstream outfile;
    			//Open the File
    			infile.open("C++Features.txt", ios::in);
    			//Ensure File exists
    			if (!infile)
    			{
    				cout << "File does not exist!\n\n";
    			}
    			//Close the file
    			infile.close();
    		}
    		else if (choice == '4')
    		{
    			//Tell user to have nice day
    			cout << "A thousand blessings upon you and your family.\n";
    			cin.get();
    			cin.ignore();
    	}
    
    	} while (choice != '4');
    
    	return 0;
    
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    In each of your menu choices you define an infile variable. When the closing brace occurs, the variable is now out of scope and can't be used any further in the program.

    Just define one infile variable for the entire main() function.

    Comment

    Working...