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.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
usingnamespace 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...