-
Help sorting a text file
What I need to do is:
1. Define a class called Student, which includes ID, FirstName, LastName, and Email.
2. Write programs to read the records from the file, sort the records on ID, and output them to a new file in the following order:
ID
FirstName LastName
Email
What I need to know is what function should I use to read the info in from the text file to my student class. Fstream does not seem to have one built in, at least I have been unable to find any info on it so far. Could I use fgets to do it? If anyone could point me in the right direction I would appreciate it. And sorry I don't have any code but since I don't really know what to use I can't do much. Thanks in advance.
-
You could probably use the read, get or getline member functions to do what you wish or even just use the stream extraction operator >>. It depends on what the source data looks like.
-
ok...
Ok I originally tried using a get function to get the info but that was all funky. So I tried using the extraction operator >> and it worked but only for the first line. Heres my current code:
Code:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (void){
char ch;
int char_count = 0;
string student;
fstream iFile("e:/Classlist.txt");//Open Classlist.txt from hdd
if (! iFile){
cout << "Error opening input file" << endl;
cin.get ();
return -1;
}//End if
iFile>>student;
cout<<student;
cin.get();
return 0;
}
So now I must ask, how can I get the extraction operator to read all the lines of the file? Well, I'll go check it out, but if anyone has any tips/hints/links that would be great.
Again thanks for any help!
-
Could you post a sample of what the input file looks like, a couple records worth of data perhaps?
Using an fstream object, you are required to have at least two arguments I believe. The second argument is the mode you intend to open the file as. There is no default for this second argument so something must be supplied. For a file you intend to read from this should be ios::in at the very least, i.e.:
Code:
fstream iFile("e:/Classlist.txt",ios::in);
Or easier still just use an ifstream object where the ios::in is implied (a default):
Code:
ifstream iFile("e:/Classlist.txt");
Each of the functions read, get, and getline have many different versions depending on what type of arguments and how many arguments you provide to them so any issues you had with the get member function could have been due to some confusion.
-
no matter what (fgets, read, get, getline, etc) you use to read a given students info the following two lines
iFile>>student;
cout<<student;
will need to be put into a loop to deal with this question:
>>how can I get the extraction operator to read all the lines of the file? The exact syntax of the loop conditions will depend on which method you use to read the file, what structure the file contents have, etc.