Hi all,
I am new in c++ programming and I am trying to make some examples
But unfortunately I have some problems

My code is :

#include <iostream>
#include <string>
    
using namespace std;

int main()
{
        string firstname, lastname, fullname;

        cout << "First name: ";
        cin >> firstname ;
        cout << endl;
        
   
        cout << "Last name: ";
        getline (cin, lastname);



        fullname = lastname + ", " + firstname;
        cout << "Fullname: " << fullname << endl;
   
     
system("pause");
return 0;
}

I am using Dev-C++ so the line 'system("pause");'

The problem I have is that getline function does not work.
What am I doing wrong

Try

cin.flush(); or cin.clear();
fflush(stdin);

at line number 14.

Thanks a lot but what is exactly the problem with my code ?
when I am trying only getline function it works.

Its a I/P stream Related Issue.
The cin that u used to get leaves a \n char in the stream. hence the cin.getline accepts that and ignores wat ever u type.
So u need to flush the input stream to get a new string.

@bufospro: It is not a problem with your code. it is just a matter of clearing the input stream.

Never flush the input stream with fflush

fflush( stdin); // wrong!

There is a sticky on this forum that nicely explains how to deal with this problem.

Edited 6 Years Ago by thelamb: n/a

Never flush the input stream with fflush

fflush( stdin); // wrong!

There is a sticky on this forum that nicely explains how to deal with this problem.

Yes I agree with u.
cin.ignore or cin.clear are better options

This question has already been answered. Start a new discussion instead.