Hello there, I am a complete new beginner here. I am trying to load a .txt file which contains a few variables and display them. I am not sure how to access private members so I have set them all to be public. how can I make my public class members to private and be able to access from my main.cpp script?
Here is what I have done so far.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main ()
{
ifstream myfile("patient1.txt");
string Name;
string DOB;
int Nscan;
string File;
int N;
if (!myfile)
{
cout << ("Error: data.txt not found");
}
patient_data patient_data [5];
for(int i = 0; i < 5; i++)
if(myfile >> Name >> DOB >> Nscan >> File>> N)
{
patient_data [i].setName(Name);
patient_data [i].setDOB(DOB);
patient_data [i].setNscan(Nscan);
patient_data [i].setFile(File);
patient_data [i].setN(N);
Why should the main() have to access private members of some class type?
Look at your code. How do you set the members of a patient? The main() does not access them. Your class has five public member functions (all names start with "set").
Hi there, thank you for you help.
I have another question.
This patient1.txt also includes the name of another txt file called MRI.txt as following;
Ben
13/07/1950
1
MRI.txt
1
I would like to also display MRI.txt once the patient1.txt is loaded and put the variables in the MRI.txt into private classes. The contents of MRI.txt are as follow;
I am getting an error when opening the MRI.txt file.
as in "Error: MRI.txt not found" maybe?
If that is the error your .txt file is not where the program expects to find it. Usually in the same location as your .exe file.
If you are using an IDE such as Visual Studio, and running the program from within the IDE requires the .txt file to be where your source files are located.
I am using Xcode and I have both text files saved in the same locations. The patient1.txt file is being read but the MRI.txt is not loading at all. Is there any other way to load the variable "File" which corresponds to "MRI.txt" ?
string File;
for (int i = 0; i < 4; i++)
if (myfile >> Name >> DOB >> Nscan >> File)
patient[i].get(Name, DOB, Nscan, File);
myfile.close();
ifstream myMRIFile;
myMRIFile.open("File");
You do read a filename from myfile and store it in string File.
However, you do attempt to open a file that is literally named "File".
If you want to use the name stored in the variable, then you have to use the
variable: myMRIFile.open( File );
You do have a second issue. You do read data of four patients. Each presumably has their own MRI data. However, you don't read MRI for each patient. You do it after all patients. If the string File still holds a valid name, it is the name from the last patient's entry.
Your could:
1 2 3 4 5 6
for (int i = 0; i < 4; i++) {
if (myfile >> Name >> DOB >> Nscan >> File) {
patient[i].get(Name, DOB, Nscan, File);
// read MRI data for patient[i] from File
}
}