getline() Function and Character Array in C++
The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered. Must read the article getline(string) in C++ for more details.
In C++, stream classes support line-oriented functions, getline() and write() to perform input and output functions respectively.
Getline Character Array: This function reads the whole line of text that ends with a new line or until the maximum limit is reached. getline() is the member function of istream class.
// (buffer, stream_size, delimiter) istream& getline(char*, int size, char='\n') // The delimiter character is considered as '\n' istream& getline(char*, int size)
- char*: Character pointer that points to the array.
- Size: Acts as a delimiter that defines the size of the array.
The Function Does the Following Operations:
- Extracts character up to the delimiter.
- Stores the characters in the buffer.
- The maximum number of characters extracted is size – 1.
Note: that the terminator(or delimiter) character can be any character (like ‘ ‘, ‘, ‘ or any special character, etc.). The terminator character is read but not saved into a buffer, instead it is replaced by the null character.
Input: Aditya Rakhecha
Your Name is:: Aditya Rakhecha
Explanation: In the above program, the statement cin.getline(str, 20); reads a string until it encounters the new line character or the maximum number of characters (here 20). Try the function with different limits and see the output.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.