Link to home
Start Free TrialLog in
Avatar of BrianGEFF719
BrianGEFF719Flag for United States of America

asked on

GetLine() Question

I am using get line to store a string:

this is an example program:


#include <iostream>
#include <string>
#include <iomanip>

int main()
{
string strName;

cout << "Enter Name: ";
getline (cin, strName);

return 0;
}

the problem is that when I use get line, you have to hit enter twice. What will happen is, I will hit enter it will move to the next line, but I have to hit enter again for input to terminate.


Why is it doing this?

-Brian
Avatar of Mysidia
Mysidia
Flag of United States of America image

That's rather unusual.. which compiler version/OS environment?
Avatar of BrianGEFF719

ASKER

Visual C++ 6.0
VC++ 6, Windows XP SP2
ASKER CERTIFIED SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
On a WinXP VC 6.0 environment happens the same. It is because of that sequence in <string> include file:

        for (; ; _C = _I.rdbuf()->snextc())
            if (_Tr::eq_int_type(_Tr::eof(), _C))
                {_St |= ios_base::eofbit;
                break; }
            else if (_Tr::eq((_E)_C, _D))
                {_Chg = true;
                _I.rdbuf()->snextc();
                break; }
            else if (_X.max_size() <= _X.size())
                {_St |= ios_base::failbit;
                break; }
            else
                _X += _Tr::to_char_type(_C), _Chg = true;

The first 'else if'  truely finds out that the terminating character was entered *but* calls again _I.rdbuf()->snextc(); So you have to hit <Enter> again. I don't know if that is a bug or how to overcome that strange behavior.

Regards, Alex
 
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@efn

thanks, for the answer. I am going to modify STL header file. Or should i rewrite std::string? ;-)

Regards, Alex
Avatar of teratoma
teratoma

Have you tried cin.getline?
If you want to resort to changing your own code, then you could try the simpler C stdio library
if you like...

#include <iostream>
#include <string>
#include <iomanip>
#include <cstdio>

int main()
{
  string strName;
  char buf[512];

   printf ("Enter name:");

   if ( fgets(buf, sizeof(buf), stdin) ) {
      strName = string(buf);
   } else {
      fprintf(stderr, "Error: unable to read name\n");
      return 1;
  }

  return 0;
}