2
#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?

1 Answer 1

2

Let's consider the following two lines

 cin >> marks; cin.get(ch); 

In the condition when marks is a char. Because input from cin with >>operator requires pressing Enter from user, code of Enter-key ('\n') will be also in the input buffer.

If you do not remove this '\n' from input buffer, at the next iteration of your loop cin.get(name,30); will read this single character to name.

It was an example for cases when marks is a char.

In case of incorrect input, e.g. user inputs

 4vv6s5 

as a mark (and marks variable is of float type) 4 will be taken to marks, and "vv6s5" to name of next student.

So a better way for cleaning input buffer after input can be as follows:

cin >> marks; do{ cin.get(ch); } while(ch != '\n'); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.