I/O, if statement

closed account (2EURX9L8)
Brain is not functioning due to sleep deprivation....

say if you had these instructions:

Write a program that calculates and prints paycheck information. The program is to work with a file that has all the information for one employee. From a user, get the name of the input file. This filename is to include the extension and will not contain any spaces. If the file doesn’t open, display an error message and shut the program down. The file contains the following information for one employee.


How would you go about it? Here is what I have so far

1
2
3
4
5
6
7
8
9
	cout<<"Please enter the file name of the employees data with no spaces and the file extension: ";
				cin>>fileName;
				//if (fileName=="johnHolden.txt")
				inFile.open("johnholden.txt");
	
						if(!inFile)
							{cout<<"Error opening file\n";
							return 0;}
		


the // line is something I probably don't need to do and am doing it wrong anyway, but if I were, how would you go about getting a file name from a user and if it isn't a file that is included in your code, display an error message?
I'm not 100% on this since I'm learning all of this too, but couldn't you do
1
2
3
string fileName;
cin >> fileName;
inFile.open(fileName);

?
closed account (2EURX9L8)
1
2
3
4
5
6
7
8
string fileName;
cout<<"Please enter the file name of the employee\nwith no spaces and with the file extension: ";
				cin>>fileName;
				inFile.open("johnholden.txt");  //instructions to open file
					
				if(!inFile)  //code to display an error if there is an error in opening the file
					{cout<<"Error opening file\n";
					return 0;}


I guess I am just going to go with this, I am pretty sure its a simple solution but I am so very lost.

I'm not 100% on this since I'm learning all of this too, but couldn't you do
1
2
3
string fileName;
cin >> fileName;
inFile.open(fileName);

?

Almost, fstream does not support passing strings directly into it (this might be changed for the latest C++ update, but shouldn't apply right now anyway). Seeing as fstream only supports const char* you need to add .c_str() to the end of the string for it to work.

Something like this should work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   string Filename;

	   cout << "Enter a filename to search for" << endl;
	   cin >> Filename;

	   fstream File;
	   File.open(Filename.c_str());  // opens the file the user requested 

	   if(File.good())  // checks if file exists
	   {
		   //Read stuff from file 
	   }

	   else   //prints error message
	   {
		   cout << "File does not exist" << endl; 
	   }
Topic archived. No new replies allowed.