getline()
istream& getline (istream& is, string& str, char delim);
It reads the input from the sequence of characters entered by user until a new line character(\n) is found. It then replaces the str by the newly extracted sequence.
Getting an Input from user
#include <iostream> int main() { std::string word = ""; getline(std::cin, word, ' '); std::cout<<"User Entered word is " << word << std::endl; return 0; }
shirley
hello
User Entered word is shirley
hello |
Let's see what is happening in the below program.
#include <iostream> int main() { std::string userInput; std::cout << "Enter User Input: \n"; std::cin >> userInput; std::string userLament; std::cout << "Enter User Lamentations: \n"; std::getline(std::cin, userLament); std::cout << "\nuserInput " << userInput << " userLament " << userLament << std::endl; return 0; }
Click here to debug.
My program first reads a string with cin >> userInput, and then a line with getline(cin, userLament).
The user types a string, followed by the ENTER key. The cin >> userInput will read the string, but the ENTER key, interpreted as a newline character, will be left in the input buffer.
When your program then goes on to read a complete line with getline(cin, userLament), it will read the very short line that consists of just that left-over newline character. This looks like the program "skips to the next read".
Comments
Post a Comment