C++ program to read string using cin.getline()

C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from the input stream and adds them to the given string object until it determines that the character is delimiting. If any, the value stored in string object str shall be replaced with the current string when doing so. The function getline() can be reproduced in two ways:

  • Syntax:

Parameters:

Delim: This is the delimitation character that tells the function to stop reading further input after the character is reached.

Str: It is a string object, and the input is stored within this object after reading from the stream.

Is: It is an istream class object, and tells the stream function from where to read the input.

Return Value: This function returns the same input stream as the parameter which is accepted.

  • Syntax:

The second statement is closely parallel to that of the first. The only difference is that this latter doesn’t recognize any delimitation character.

Parameters:

Is: is an istream type object and informs the stream function where the data should be read from.

Str: It is a string entity, and after reading from the source, the input is stored within that object.

Return Value: This function will return a certain input stream as the parameter which is accepted.

Name, address, about a person and print in different lines will be read in this program, the name will contain spaces and dots, the address will contain space, commas, and other special characters, as well as mixed characters, will be included in this program. Using the cin.getline() function, we can read all data, and print using cout.

cin.getline() example in C++

Output:

C++ program to read string using cin.getline()

Example 2: We can use the function getline() to split a sentence according to a character. Let’s look at an example to see how that can be done.

Output:

C++ program to read string using cin.getline()

Caution: This function considers a new line or (‘\n’) character to be valid input for this function as the delimitation character and new line character.

Example2:

Output:

C++ program to read string using cin.getline()

Pin It on Pinterest

Share This