getline() is a standard library function in C++ and is used to read a string or a line from input stream. It is present in the <string> header.
- Syntax 1:
istream& getline (istream& is, string& str, char delim);
is : It is an object of istream class and tells the function about the stream from where to read the input from.
str : It is a string object, the input is stored in this object after being read from the stream.
delim : It is the delimitation character which tells the function to stop reading further input after reaching this character.
- Syntax 2:
istream& getline (istream& is, string& str);
The second declaration is almost same as that of the first one. The only difference is, it does not accept any delimitation character. This function consider new line or (‘\n’) character as the delimitation character.
So basically, what the getline function does is extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.
Note: The previous stored value in the string object str will be replaced by the input string if any.
What does getline() returns?
As we can see in the prototype declared above, the return type of this function is also of type istream. This functions return the same input stream as is which it accepts as parameter.
Hello, Harsh Agarwal welcome to GfG!
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- How to use getline() in C++ when there are blank lines in input?
- getline() function and character array
- std::string::append vs std::string::push_back() vs Operator += in C++
- Check if a string can be formed from another string using given constraints
- std::string::replace , std::string::replace_if in C++
- std::string::replace_copy(), std::string::replace_copy_if in C++
- std::string::remove_copy(), std::string::remove_copy_if() in C++
- string at() in C++
- std::string::insert() in C++
- std::string::resize() in C++
- std::string::clear in C++
- std::string::erase in C++
- std::string::compare() in C++
- std::string::push_back() in C++
- std::string::data() in C++