getline function not working

Hi,

I have been trying to figure out the mistake for a long time,but I failed to do.Please look at it the ode in the below and let me know where I did the mistake

if(ch == 'N')
{
cout <<"Name? ";
get_name(name);
cout <<"Name is " << name << endl;
}

void get_name(string &name)
{
getline(cin,name);
}


The output look like in the below..
Select: N
Name? Name is

What is the ch and the name variables? Are they called before this? This code is imcomplete as is so I'm not too sure what it is you want.
I could be very wrong here but I will attempt to help. You might have to change the type of your function get_name from void to string and return name.I say to try this since technically you would be returning a string value that is stored in your variable name via the getline function.
Last edited on
He's fine. He passed in name by reference so when the function ends, it'll return it automatically.
I can guess that the problem is in the input before using get_name. For example

1
2
3
4
5
6
7
8
9
10
char ch;

std::cin >> ch;

if ( ch == 'N' )
{
   std::cout << "Name? ";
   get_name( name );
   std::cout << "Name is " << name << std::endl;
}


After entering 'ch' the new line character is still in the input buffer. So the next getline reads an empty string. You should ignore the new line character after the statement std::cin >> ch;
That is exactly the problem.

The user will always press ENTER after every input you ask him for. Make sure to clear it.

1
2
3
string s;
cout << "What is your name? ";
getline( cin, s );  // ENTER is automatically removed from input 

1
2
3
4
float x;
cout << "What is the airspeed velocity of an unladen swallow? ";
cin >> x;  // ENTER is not automatically removed
cin.clear( numeric_limits <streamsize> ::max(), '\n' );  // so do it here 

Hope this helps.
Topic archived. No new replies allowed.