I have this code which works fine but I cant comprehend the meaning of cin.get(ch) in the for loop. I tested the program after removing it and the first input comes fine but as soon as loop runs for the second time, program does not wait for the user to input "name" and skips automatically to "marks".

#include<iostream.h>
#include<fstream.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{       clrscr();
    int marks;
    char name[40];
    char ch;
    ofstream a("STUDENT.txt",ios::app);
    char ans='y';
    while(ans=='y'|| ans=='Y')
    {   cout<<"\nEnter name of student: " ;
        cin.getline(name,40);
        cout<<"Enter marks of student: ";
        cin>>marks;
        cout<<"Want to enter more? (y/n)";
        cin>>ans;
        cin.get(ch);
        a<<"\n"<<name<<"\n"<<marks;
        }
    a.close ();
    getch();
    }

Recommended Answers

All 3 Replies

You can learn all about this problem here

Thanks for your reply but the link is overly intricate.
I am unable to understand the actual problem as I am complete novie in C++.

The jist of the issue is >> leaves the "enter key" in the input buffer. If you don't remove it before getline() is used then getline() will see the "enter key" and grab it. Since getline() reads until it sees an "enter key" and then returns you wont get anything.

BTW when I say "enter key" what really is in the buffer is a newline character. with text based programing it is often assumend that once a newline is encountered it is the end of the input since the only easy way to insert a newline into the input buffer is to press enter.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.