Reading In Deletes My .txt File

I'm working on a program that will read in from a text file and store in a person struct, but what seems to happen is that whenever I try to read in even just a simple name or line, it just removes all text from the .txt file.

Here is a look at my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <string>
#include <vector>
#include <fstream>

using namespace std;

struct Person{
	string firstName;
	string lastName;
	char sex;
	int age;

};

void fillVector(){
	string fileName;
	
	ofstream dataOut;
	ifstream dataIn;
	fstream filestream;
	bool run = true;
	string tempLast;
	string tempFirst;
	
	while(run==true){
		cout << "Please enter the name of your file: ";
		cin >> fileName;
		filestream.open (fileName);
  
		if (filestream.is_open()){
			cout << "File successfully opened.\n";
			filestream.close();
			run=false;
		}
		else{
			cout << "Error opening file, please check if the file name you entered was correct.\n";
		}
	}
	
	dataIn.open(fileName);
	dataOut.open(fileName);
		
		while(!dataIn.eof()){
			getline(dataIn, tempLast);
			cout << tempLast;
		}
		
		if(dataIn.eof()){
			cout << "End of file reached.\n";
		}
}


The current text that is in my .txt file is "Anderson". My goal would be to run the program and after I type in the file name, have "Anderson" be output to my console. After running the program, the text file is cleared of any text I put in. Right now all that is being output is.

Please enter the name of your file: namefile.txt
File successfully opened.
End of file reached.
Press any key to continue...
The description of this project implies the file will be opened for input. This is what is done.
1
2
	ifstream dataIn;
	dataIn.open(fileName);


However, for reasons not explained in the description, there is also this code:
1
2
	ofstream dataOut;
	dataOut.open(fileName);

Here the same filename is opened for output. Using the default settings as here, will cause the length of the file to be set to zero.

I don't understand the intention of the ofstream. Right now I'd suggest removing it as it is the direct cause of the problem.
Last edited on
You were exactly right, I deleted those lines and it now works as expected. Thank you!
Topic archived. No new replies allowed.