Search code examples
c++filegetfile-handlingread-write

Significance of get() in the C++ snippet


This is a problem relating to file handling where we input data to a file and then display its contents. I am unable to understand how the line cin.get(ch); helps in the output. I found that if I remove this line from the code, the program is unable to take the input for the variable marks in the second iteration. Why is it so ? I am a bit confused in the working of get() here. My code:

 #include<iostream>
 #include<conio>
 #include<fstream>
 int main()
 {

  ofstream fout;
  fout.open("student",ios::out);
  char name[30],ch;
  float marks=0.0;
  for(int i=0;i<5;i++)
  {
   cout<<"Student "<<(i+1)<<":\t Name:";
   cin.get(name,30);
   cout<<"\t\t Marks: ";
   cin>>marks;
   cin.get(ch); **// the confusion is in this line**
   fout<<name<<"\n"<<marks<<"\n";
  }
  fout.close();
  ifstream fin;
  fin.open("student",ios::in);
  fin.seekg(0);
  cout<<"\n";
  for(i=0;i<5;i++)
  {
   fin.get(name,30);
   fin.get(ch);
   fin>>marks;
   fin.get(ch);
   cout<<"Student Name: "<<name;
   cout<<"\t Marks: "<<marks<<"\n";
  }
  fin.close();
  return 0;
}

Solution

  • From the description of the function

    basic_istream<charT,traits>& get(char_type* s, streamsize n,
    char_type delim );
    

    in the C++ Standard:

    Characters are extracted and stored until any of the following occurs: ...

    — traits::eq(c, delim) for the next available input character c (in which case c is not extracted).

    And from the description of the function

    basic_istream<charT,traits>& get(char_type* s, streamsize n);
    

    Effects: Calls get(s,n,widen(’\n’))

    Thus this call

    cin.get(ch); 
    

    serves to extract the new line character from the input buffer. Otherwise a next call of the function

    cin.get(name,30);
    

    will read an empty string.

    Instead of the call

    cin.get(ch); 
    

    you could use a call of the member function ignore