jeudi 24 décembre 2015

File reading and writing in c++

#include<iostream> 
#include<fstream> 
using namespace std; 
int main() 
{ 
ofstream fout("student",ios::out); 
char name[30],ch; 
float marks=0.0; 
for(int i=0;i<5;i++) 
{ 
cout<<"Stud"<<(i+1)<<":\tName"; 
cin.get(name,30); 
cout<<"\tMarks"; 
cin>>marks; 
cin.get(ch); 
fout<<name<<'\n'<<marks<<'\n'; 

} 
fout.close(); 
ifstream fin("student",ios::in); 
fin.seekg(0); 
cout<<"\n"; 
for(int i=0;i<5;i++) 
{ 
fin.get(name,30); 
fin.get(ch); 
fin>>marks; 
fin.get(ch); 
cout<<name<<marks; 
} 
fin.close(); 
} 

Now, there are two things I don't understand..why do you need cin.get(ch) while writing to the file(My textbook says to clear the input buffer). How does it help in doing so? I don't have much knowledge about the clearing of a buffer and How does it affect the following iterations?

Further, what if I don't separate the name and marks while writing to the file with a '\n'? And, while reading I read it like fin>>get(name,30); fin>>marks; Upon running the program I noticed that only the first iteration's values are being repeated 5 times. Why is this so?

Aucun commentaire:

Enregistrer un commentaire