Computing.Net > Forums > Programming > Reading from a text file in C++

Reading from a text file in C++

Reply to Message Icon

Original Message
Name: Unnameable
Date: December 28, 2003 at 12:06:00 Pacific
Subject: Reading from a text file in C++
OS: Win XP
CPU/Ram: cel 700 / 256MB
Comment:

I'm wanting to have my program write data to a text file, and then have the ability to read back from it... so far I can get it to write to the file...but I'm damned if I can get it to read from it! Anyone have any idea what is wrong with my coding below?

void SaveToFile()
{
int index;

//create output file

ofstream outfile("Appointments.txt", ios::out);

//save data to text file

for (index=0; index < CurrentSize; index++)
{
outfile<<AppRecord[index].Name<<endl;
outfile<<AppRecord[index].Description<<endl;
outfile<<AppRecord[index].Date<<endl;
outfile<<AppRecord[index].Time<<endl;
}


outfile.close(); //close output file

}

void LoadFromFile()
{
CurrentSize = 0;

//open input file

ifstream infile("Appointments.txt", ios::in);

//read data from file

while (!infile.eof()) //reads data until end of the file is reached
{
infile>>AppRecord[CurrentSize].Name;
infile>>AppRecord[CurrentSize].Description;
infile>>AppRecord[CurrentSize].Date;
infile>>AppRecord[CurrentSize].Time;
infile.get();

CurrentSize +=1; //increments size of array pointer
}

infile.close(); //close input file
cin.get();
CurrentSize = CurrentSize -1;
}


Report Offensive Message For Removal

Response Number 1
Name: Unnameable
Date: December 28, 2003 at 13:24:54 Pacific
Subject: Reading from a text file in C++
Reply: (edit)

Forgot to say....

the program compiles and runs fine...but hangs when I try to run the LoasdFromFile function.


Report Offensive Follow Up For Removal

Response Number 2
Name: Godgory
Date: December 31, 2003 at 14:44:07 Pacific
Subject: Reading from a text file in C++
Reply: (edit)

Whe I don't know what's wrong, I always use the wath and run the program step by step (usually line by line) or using breakpoints.
This way you'll know wich line doesn't work or if the values of the variables are wrong.
The watch and step by step running gets you out of every mess.



Report Offensive Follow Up For Removal

Response Number 3
Name: raylu
Date: January 3, 2004 at 10:17:27 Pacific
Subject: Reading from a text file in C++
Reply: (edit)

I'm not too good at reading from a file either, but what is CurrentSize in your SaveToFile? The file may be so big that it takes a long time for C++ to read it all. Have you tried just reading one AppRecord from the file? Take away the for loop at LoadFromFile() and see what happens.


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Reading from a text file in C++

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software