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

Recommended Answers

All 7 Replies

Try

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

at line number 14.

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.

OR =) use cin.ignore() inbetween your cout statement and your getline statement.

@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.

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

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.