i going through code in school textbook, wherein there line who's function clear input buffer (mentioned comment in code).
i couldn't quite understand purpose. required removal messes console input process.
please explain function is, , happening when remove it.
i have tried using cin.ignore(); , works fine too. how function used here, exact replacement of cin.ignore()?
p.s. in school using older version of c++. hence ".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 = 0; < 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 = 0; < 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(); }
cin >> marks; cin.get(ch); //for clearing input buffer (this thing!)
this not-so-robust way of clearing input buffer. if type number followed enter, first line consume number , put value in marks
while second line read newline character , discard it.
it not robust since not account spaces user might have entered after number. more robust method use istream::ignore
.
cin >> marks; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Comments
Post a Comment