fstream - cannot read file

so my code cannot read my file even though i had created a record. when i search for the record, it says record does not exist. here's the code. The part where im getting problem at is on the function void search(int n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
 #include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include<stdio.h>
#include<conio.h>
#include <windows.h>

using namespace std;

class student
{
   char Fname[200], MI[5], Lname[200], byear[4], bmonth[2], bdate[2];
   char natio[100], address[100], religion[100], prog[10];
   char hobbies[200], likes[200], disl[200], why[200], dlikes[200], num[20];
   int age, studnum, number, num1, num2;
   static bool yearEntered;
   static bool monthEntered;
   static bool dateEntered;
   
   public:
          void getdata();
          void showdata();
          int retstudnum();            
};

bool student:: yearEntered = false;
bool student:: monthEntered = false;
bool student:: dateEntered = false;

void student::getdata()
{
   cout<<setw(70)<<"Applicant's Registration Form";
   cout<<"\n\nFirst name: ";
   cin.ignore();
   cin.getline(Fname, 100);
   cout<<"\nMiddle Initial: ";
   cin>>MI;
   cout<<"\nSurname: ";
   cin.ignore();
   cin.getline(Lname, 100);
   cout<<"\nAge: ";
   cin>>age;
   cin.ignore();
      do{
	cout<<"\nBirth Year: ";
	cin>>byear;
	string s = byear;
	number = atoi(s.c_str());
	if ( number == 0 )
	cout << "Letter is not alowed :) ";	
	else	
		yearEntered = true;  
	}while(!yearEntered);	
	   do{
	cout<<"\nEnter Birth Month (ex. 01): ";
	cin>>bmonth;
	string s = bmonth;
	num1 = atoi(s.c_str());
	if ( num1 == 0 )
	cout << "Letter is not alowed :) ";	
	else	
		monthEntered = true;  
	}while(!monthEntered);	
	   do{
	cout<<"\nEnter Birth day: ";
	cin>>bdate;
	string s = bdate;
	num2 = atoi(s.c_str());
	if ( num2 == 0 )
	cout << "Letter is not alowed :) ";	
	else	
		dateEntered = true;  
	}while(!dateEntered);	
    cin.ignore();	
   cout<<"\n\nAddress: ";
   cin.getline(address, 100);
   cout<<"\nReligion: ";
   cin>>religion; 
   cout<<"\nMobile Number: ";
   cin.ignore();
   cin.getline(num, 20);
   cout<<"\nProgram/Year: ";
   cin>>prog;
   cout<<"\nStudent number: ";
   cin>>studnum;

   cout<<"\nLikes: ";
   cin.ignore();
   cin.getline(likes, 100);
   cout<<"\nDislikes: ";
   cin.getline(dlikes, 100);
   cout<<"\nWhy JPCS?: ";
   cin.getline(why, 100);
}

void student::showdata()
{
   cout<<"\n\nFirst name: "<<"\t"<<Fname;
   cout<<"\nMiddle Initial: "<<MI;  
   cout<<"\nSurname: "<<"\t"<<Lname;   
   cout<<"\nAge: "<<"\t\t"<<age;   
   cout<<"\nBirthday: "<<"\t"<<bmonth<<" - "<<bdate<<" - "<<byear;   
   cout<<"\nAddress: "<<"\t"<<address;   
   cout<<"\nReligion: "<<"\t"<<religion;    
   cout<<"\nMobile Number: "<<"\t"<<num;  
   cout<<"\nProgram/Year: "<<"\t"<<prog; 
   cout<<"\nStudent number: "<<studnum;   
   cout<<"\nLikes: "<<"\t\t"<<likes;   
   cout<<"\nDislikes: "<<"\t"<<disl;  
   cout<<"\nWhy JPCS?: "<<"\t"<<why;
}

int student::retstudnum()
{
	return studnum;
}

//-------------------------- 
//function declarations     
//---------------------------

void register_form();
void search(int);
//----------------------------
// MAIN FUNCTION
//----------------------------

int main()
{
    char choice;
    int n;
    
    do
    {
        system("cls");
		cout<<setw(50)<<"Junior Philippines Computer Society";
		cout<<setw(60)<<"\n\nMAIN MENU";
		cout<<"\n\n\t01. Register as an applicant";
		cout<<"\n\n\t02. Search for applicants";
		cout<<"\n\n\t03. EXIT";
		cout<<"\n\n\tPlease Select Your Option (1-3) ";
		cin>>choice;
		system("cls");
		switch(choice)
		{
			case '1': register_form();
  	                  break;
			case '2': cout<<"\n\n\tPlease enter student number: ";
                      cin>>n;
                      search(n);
				      break;
			case '3':
				      break;
			default :cout<<"\a";
		}
    	}while(choice!='3');
 

    system("pause<0");
    return 0;
}

void register_form()
{   
	student st;
	ofstream outFile;
	outFile.open("applis.dat",ios::binary|ios::app);
	st.getdata();
	outFile.write((char *) &st, sizeof(student));
	outFile.close();
    	cout<<"\n\nStudent record Has Been Created ";
	cin.ignore();
	getch();
}

void search(int n)
{    
	student st;
	ifstream inFile;
	inFile.open("applis.dat",ios::binary);
	if(!inFile)
	{
		cout<<"File could not be open !! Press any Key...";
		getch();
		return;
	}

	int flag=0;
	while(inFile.read((char *) &st, sizeof(student)))
	{
		if(st.retstudnum()==n)
		{
			 st.showdata();
			 flag=1;
		}
	}
	inFile.close();
	if(flag==0)
		cout<<"\n\nrecord not exist";
	getch();
}
 
closed account (j3Rz8vqX)
Try again.

I've just tested your program, and it works.
After creating an applicant, it saved the data to the root of the projects location. I was able to access the file after that using your list command, and entering the students id.

As a reminder, you program is expecting a distinct data type when reading form file. It is expecting an object read.

Example of working program:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//Your code...

        Please enter student number: 12345


First name:     Bob
Middle Initial: -
Surname:        -
Age:            43
Birthday:       1215 - 15 - 19701215
Address:        -
Religion:       -
Mobile Number:  -
Program/Year:   -
Student number: 12345
Likes:          -
Dislikes:
Why JPCS?:      -


Edit:
Birthday: 1215 - 15 - 19701215
The projection of birth date, seems a bit off somehow...
I double "tested" it and it still produced answers of that pattern.
-
Update #1: some members were lost after input of new members.

Update #2: //Removed

Update #3:
I am no longer able to produce the errors, from #1, after flushing the data file; DOB bug still persists.

Update #4: Use cin.getline() for input from DOB; you're reading an array of characters. You did so before with First name and such. I believe this caused data members to have become dis-aligned during writing and reading from file.
Last edited on
I tried this program, (though I trimmed some of the input to save typing lots of optional stuff (including middle initial which may not always be present).

It worked except on one occasion when I had the output file open in another application. That identified a flaw, there's no error checking when writing to the file. I added this code to function register_form():
1
2
3
4
    if (outFile)
        cout<<"\n\nStudent record Has Been Created ";
    else
        cout << "\n\n Error saving to file"; 


Also, since it isn't easy to browse the file to see what's there, I added a diagnostic option:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void listStudents()
{
    student st;
    ifstream inFile(filename, ios::binary);
    if(!inFile)
    {
        cout<<"File could not be open !! Press any Key...";
        getch();
        return;
    }

    while(inFile.read((char *) &st, sizeof(student)))
    {
        cout << setw(10) << st.retstudnum()
             << setw(30) << st.getfirst()
             << setw(30) << st.getlast()
             << endl;
    }

    cout<<" == end of list ==" << endl;
    getch();

}

as well as within class student
1
2
       std::string getfirst() const { return Fname; };
       std::string getlast()  const { return Lname; };

and adding option 4 to the menu to call the new function listStudents().

That was not meant to be particularly good style, just a quick way to view the file.

Note, ifstream inFile(filename, ios::binary); here i declared filename as a constant string to avoid the possibility of different filenames being used throughout the program.
Last edited on
Topic archived. No new replies allowed.