Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline(cin.name) gets skipped

I call a function from a function in C++ that has the line getline(cin,name) where name is a string. the first time through the loop, the program does not wait for input. It will on all other passes through the loop. Any ideas on why?

void getName (string& name)
{ 
     int nameLen; 
      do{
          cout << "Enter the last Name of the resident." << endl << endl
              << "There should not be any spaces and no more than 15"
              << " characters in the name."  << endl;



         getline(cin,name);
            cout << endl;
            nameLen = name.length();// set len to number of characters input

         cout << "last" << name << endl;
         }
      while (nameLen < LastNameLength);   
      return;
}
like image 931
user1060993 Avatar asked Dec 28 '22 10:12

user1060993


2 Answers

Make sure there isn't left overs since the last time you read something from cin, like:
In an earlier point in your program:

int number;
cin >> number;

The input you give:

5

Later in the program:

getline(cin,name);

and getline will seem to not be called, but rather it collected the newline from the last time you took input because when you use cin >> it leaves new lines.

like image 57
Dani Avatar answered Jan 04 '23 18:01

Dani


It may be because of the input stream. The getline function stops reading input after is receives the first newline char. If for example there are multiple newlines within the buffer of std::cin - the getline will return every time it encounters one.

Check the input you are expecting.

like image 32
Adrian Cornish Avatar answered Jan 04 '23 17:01

Adrian Cornish