I can't get cin.getline to work properly, I'm using it inside a for loop.. it gets the input sucessfuly when the loop is executed for the first time(i=0), but it doesn't wait to take any input on the next times..the program just moves to the next line..

#include <iostream.h>

    struct test {
        char str[300];
        int num;


int main()

    for(int i=0; i<3; i++)
        cout <<"-Enter Name No.:" <<i+1 <<endl;
        cin.getline(t[i].str , 200);

        cout <<"-Number: ";
        cin >>t[i].num;

        for(i=0; i<3; i++)
        cout <<t[i].str <<endl;

        return 0;

here is a sample execution:

-Enter Name No.:1
-ID: 45
-Enter Name No.:2

As you see, it didn't wait to take input the second time, it moved to the next line..
one more thing, when I don't use cin inputs after getline (in the same loop, it works just fine !

any help would be appreciated :)


Thanks, I found solution .. I've to use cin.ignore() to clear the bufffer..

The problem you're experiencing is the result of cin leaving behind a trailing newline behind in the input buffer. This doesn't cause problems as long as you continue using cin, because it trashes the newline left behind from the previous call.

As soon as you start using getline, however, you run into problems because getline() doesn't trash the newline that cin leaves behind. It looks as though the program completely skipped the statement.

The quick-and-dirty solution is to clear the input buffer after using cin:

// the first parameter is the largest number of characters to skip
// before encountering the token (in this case, the newline)
// numeric_limits<streamsize>::max is the largest number of
// characters that can be in the stream
// you should probably #include <limits>
cin.ignore(numeric_limits<streamsize>::max(), '\n');

The other more-robust method is to use getline() for all your input. This isn't as hard as it sounds.

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.