getline(cin.name) gets skipped

2019-05-06 06:12发布

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;
}

3条回答
放荡不羁爱自由
2楼-- · 2019-05-06 06:44

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.

查看更多
霸刀☆藐视天下
3楼-- · 2019-05-06 06:51

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.

查看更多
Animai°情兽
4楼-- · 2019-05-06 06:56

Do you have any: cin << variableName;

lines of code? I ran into getline() skipping run-time errors when I was using:

cin << intvariable and subsequently getline(cin, variable).

This is because the cin stream object holds a buffer of input. When you enter the newline character I assume it is trunacated from the stream going to the variable asisgnment, yet is still contained within the cin object instance itself.

One workaround I used is cin.ignore(); after the cin << integer statement.

Another user mentioned parsing all input from getline into integers, floats - not root beer -, and strings. Good luck and check your code for the dual use of cin & getline().

查看更多
登录 后发表回答