Getline (cin.name) is skipped

I call a function from a function in C ++ that has a getline(cin,name) string, where name is a string. for the first time through the loop, the program does not wait for input. He will be on all other passages 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; } 
+4
source share
3 answers

Make sure that since the last time you read something from cin, there are no traces left, for example:
At an earlier point in your program:

 int number; cin >> number; 

The input you give is:

 5 

Later in the program:

 getline(cin,name); 

and getline , it seems, will not be called, but rather they have been collecting a new line since the last input, because when you use cin >> it leaves new lines.

+6
source

This may be due to the input stream. The getline function stops reading input after receiving the first new char line. If, for example, the std :: cin buffer has several lines of a new line, getline will be returned every time it encounters it.

Check your expected entry.

+2
source

Do you have: cin <variableName;

lines of code? I ran into getline (), skipping runtime errors when I used:

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

This is because the cin stream object contains an input buffer. When you enter a newline, I assume that it narrows from the stream going to the asisgnment variable, but is still contained within the cin object itself.

One workaround I've used is cin.ignore () ; after cin <integer .

Another user mentions parsing all getline input into integers, floats — not root beer — and strings. Good luck and check your code for the double use of cin and getline ().

+2
source

Source: https://habr.com/ru/post/1382625/


All Articles