jeudi 21 juillet 2016

What does clearing of input buffer mean?

I was going through a code in my school textbook, wherein there is a line who's function is to clear the input buffer (mentioned as a comment in the code).

I couldn't quite understand its purpose. It is definitely required as it's removal messes up the console input process.

Please explain what's its function, and what is happening when I remove it.

I have also tried using cin.ignore(); and it works just fine too. How is the function used here, its replacement?

P.S. In school we are using the older version of C++. Hence the ".h" extension, clrscr();, etc.

#include <iostream.h>
#include <fstream.h>
#include <conio.h>

void main(){
clrscr();

ofstream fout("student.txt", ios::out);
char name[30], ch;
float marks = 0.0;

for(int i = 0; i < 5; i++){
    cout << "Student " << (i+1) << ":\tName: ";
    cin.get(name,30);
    cout << "\t\tMarks: ";
    cin >> marks;
    cin.get(ch);  //for clearing input buffer (This thing!)
    fout << name << '\n' << marks << '\n';
}

fout.close();

ifstream fin("student.txt", ios::in);
fin.seekg(0);
cout << "\n";

for(int i = 0; i < 5; i++){
    fin.get(name,30);
    fin.get(ch); //Again
    fin >> marks;
    fin.get(ch); //Same
    cout << "Student Name: " << name;
    cout << "\tMarks: " << marks << "\n";
}

fin.close();
getch();

}

Aucun commentaire:

Enregistrer un commentaire