Opening, displaying and closing a file question

Hey all, file question. I have a saved file on my computer that I need this program to open, display and close. It's giving me one error, and it's as follows:

133 18 C:\Users\Christopher Mangum\Documents\School\C++\project4_chris_mangum.cpp [Error] 'Mailings' was not declared in this scope

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  	else if (input==multiMail)
	{
		fstream inputFile, Mailings;
		string value1, value2, value3, value4, value5;
	
		//Open the given file.
		inputFile.open(Mailings.txt);
		
		//Display the given file's contents.
		inputFile<<value1<<"\n\n";
		inputFile<<value2<<"\n\n";
		inputFile<<value3<<"\n\n";
		inputFile<<value4<<"\n\n";
		inputFile<<value5<<"\n\n";
		
		//Close the given file.
		inputFile.close();
	}


What am I doing wrong here?
quotes.

Other points and errors:
- The fstream is a stream to a file; it's not the file itself. Typically you'd have a different variable for the path to the file that has a name like file_name, which you can then mention if something went wrong. Common names for fstream variables are "ifs", "fin", or for output, "ofs", "fout". Notice how the latter two options kinda look like cin and cout, which are really short for "console in/out".
- Helps to be more exact on the kind of fstream you want. In this case, an input file, so an ifstream.
- This would've helped you get the next lines correct, which would now be syntax errors. To get data from an input stream object, use the operator >>, just line you would with cin. The operator << is used to output to the stream, just like with cout or an ofstream.
In fact, of the two mentioned operators, ifstream can only use >>, and similarly ofstream can only use <<.
- Don't need to explicitly call .open on an ifstream; the constructor is smart enough
- You should also check if the file open succeeded. It's possible you've placed the file in the wrong directory, or another process is using the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string input_file_name("Mailings.txt");
ifstream ifs(input_file_name);
if (!ifs)
{
    cout << "Error: unable to open file \"" << input_file_name << "\".  "<<
            "Please check the path and/or competing processes." << endl;
    return -2;
}
int value;  // Be exact - is it an int? a double? an actual string?
// Iterate through file for items that look like value.  By default, 
//   these items should be whitespace-separated (spaces, newlines, etc.)
while (ifs >> value)
{
    cout << "Found value: "<< value << endl;
}
// Unnecessary.  Automatically closes when it goes out of scope, which is very soon.
//ifs.close(); 
Last edited on
Topic archived. No new replies allowed.