problem in file handling

Create a class 'st_rc' consisting of the following data :
Student's Name
Student's Roll Number
Student's Marks in three subjects.

Now use this class to enter record of five students in a file 'record.txt' by using some imaginary data .Now find the record of a particular roll no. from the file as desired by the user . If the roll no. doesn't exist then a new record has to be inserted for that roll no. by using the data given by the user. The new record should be inserted at second position(after the first record) in the file.

i wrote the following code for this problem but when i open the file record.txt after executing this code,it shows several unusual characters.also if i use getline to enter name, code does not work properly.plz help!


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class st_rc {

public:
string name;
string rollno;
int marks[3];
};

int main()
{
int i;
int j;
string search;
st_rc std[6];

ofstream of ( "record.txt");

cout << "enter record of five students-->name, rollno, marks in 3 subjects" << endl;



for ( i = 0; i < 5; i++ ) {
cin >> std[i].name;
cin >> std[i].rollno;

for ( j = 0; j < 3; j++ )
cin >> std[i].marks[j];

of.write ( (char *) &std[i], sizeof(std[i]) );
}

of.close();

cout << endl;
cout << "enter the rollno to be searched" << endl;
cin >> search;
cout << endl;

ifstream ifi ( "record.txt");

if ( !ifi ) {
cout << "file does not exist" << endl;
return 0;
}

for ( i = 0; i < 5; i++ ) {
ifi.read ( (char *) &std[i], sizeof(std[i]) );

if ( std[i].rollno == search ) {
cout << "rollno exists" << endl;
ifi.close();
return 0;
}
}

ifi.close();

cout << "rollno does not exist, enter record for it" << endl;
cin >> std[5].name;

for ( i = 0; i < 3; i++ )
cin >> std[5].marks[i];

std[5].rollno = search;

ifstream f ( "record.txt");
f.read ( (char * ) &std[0], sizeof(std[0]) );

ofstream ofo ( "temp.txt");

ofo.write ( (char *) &std[0], sizeof(std[0]) );
ofo.write ( (char *) &std[5], sizeof(std[5]) );

for ( i = 1; i < 5; i++ )
ofo.write ( (char *) &std[i], sizeof(std[i]) );

remove ( "record.txt" );
rename ( "temp.txt", "record.txt" );

ofo.close();
f.close();

return 0;
}




Last edited on
Topic archived. No new replies allowed.