Aug 29, 2014 at 10:56am UTC
Hello. I do not know why my file stream is reading only one record from the file.
Here is the file and function to read/write.
1 2 3 4 5 6 7 8 9 10 11 12 13
4
J13013709
Mohammad M Rahman
79.5
J14036721
Tee Fu Hao
74.9
J13022703
Lee Zhen Zhi
82.0
J13026354
Tan Shou Heng
59.3
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
int addStudent(char code[]){
struct students{
char ID[11];
char Name[35];
char grade[3];
}stud[totalStud];
//ofstream add;
fstream getinfo;
unsigned int total=0, i=0;
char cont='Y' , total_in_char[10];
getinfo.open(strcat(code, ".txt" ), ios::in|ios::out);
while (getinfo.fail()){
cout<<"Open Fail" <<endl;
getinfo.clear();
cout<<"Opening again" <<endl;
getinfo.open(strcat(code, ".txt" ), ios::in | ios::out);
}
getinfo.getline(total_in_char, 10);
total=atoi(total_in_char);
while (getinfo.good()){
getinfo.getline(stud[i].ID, 13);
getinfo.getline(stud[i].Name, 35);
getinfo.getline(stud[i].grade, 3);
i++;//////here only reading once
}
//getinfo.close();
cout<<stud[1].ID<<endl;///////here nothing shows for index 1 of stud
while (cont=='Y' ){
cout<<"Enter student ID: " ;
cin>>stud[i].ID;
cout<<"Enter student name: " ;
cin.ignore();
cin.getline(stud[i].Name, 35);
cout<<"Enter student grade: " ;
cin>>stud[i].grade;
i++;
total=total+1;
cout<<"Conitue? Y or N: " ;
while (!(cin>>cont) || (cont!='Y' && cont!='N' )){
cout<<"Choose Y or N: " ;
cin.clear();
cin.ignore();
}
}
//add.open(code, ios::out);
//if(add.is_open())
// cout<<"File opened"<<endl;
//add<<total<<endl;
getinfo<<total<<endl;
for (int j=0;j<i;j++){
//add<<stud[j].ID<<endl;
getinfo<<stud[j].ID<<endl;
//add<<stud[j].Name<<endl;
getinfo<<stud[j].Name<<endl;
//add<<stud[j].grade<<endl;
getinfo<<stud[j].grade<<endl;
}
//add.close();
getinfo.close();
cout<<"Write success" <<endl;
return 0;
}
Last edited on Aug 29, 2014 at 10:57am UTC
Aug 29, 2014 at 11:07am UTC
The grade array is too short to store the string "79.5".
Aug 29, 2014 at 11:37am UTC
And since this is C++ why are you using C-strings instead of std::string? And why is grade a character type at all? Wouldn't a numeric type make more sense?
Aug 29, 2014 at 12:27pm UTC
and thank you for mentioning me at the end of line 10..
Aug 30, 2014 at 2:17pm UTC
u mean stud? lol...Jib we are progressing in class topic by topic...
Aug 30, 2014 at 2:18pm UTC
btw thanks all..it working now... but fstream do not read and write..just reads but do not write new added plus previous records to file...i changed to if and of stream then it works