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.

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
#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();

}
Last edited on
closed account (21vXjE8b)
When the code reach cin.get(name,30);, it'll read everything from the input buffer until a newline is reached.
After writing your marks, you press the enter key. This action is stored in input buffer as a newline... So, if you don't clear the buffer, the code will read only a newline every time is to write the name of the student --> You don't get any chance of writing anything.

Removing cin.get(ch);, the output will be something like:

Student Name: John     Marks: 9
Student Name:     Marks: 9
Student Name:     Marks: 9
Student Name:     Marks: 9
Student Name:     Marks: 9
So this means I can remove the fin.get(ch); at line no. 29, because 'marks' is not using a get() function, i.e. it isn't using the buffer to get its value?
Topic archived. No new replies allowed.