×

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

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:
istream& getline (istream& is, string& str, char delim);

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:
istream& getline (istream& is, string& str);

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++

/*C++ program to read string using cin.getline().*/
#include  <iostream>
using namespace std;
//macro definitions for maximum length of variables
#define MAX_NAME_LENGTH     100
#define MAX_ADDRESS_LENGTH  200
#define MAX_ABOUT_LENGTH    400
using namespace std;
int main()
{
    char name[MAX_NAME_LENGTH],address[MAX_ADDRESS_LENGTH],about[MAX_ABOUT_LENGTH];
    cout << "Enter Your name: ";
    cin.getline(name,MAX_NAME_LENGTH);
    cout << "Enter Your address: ";
    cin.getline(address,MAX_ADDRESS_LENGTH);
    cout << "Enter about yourself (press # to complete): ";
    cin.getline(about,MAX_ABOUT_LENGTH,'#');    //# is a delimiter
    cout << "\nEntered details are:";
    cout << "Name: "  << name << endl;
    cout << "Address: " << address << endl;
    cout << "About: " << about << endl;
    return 0;
}

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.

// C++ program to understand the use of getline() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    string P, K;
    getline(cin, P);
    stringstream N(P);
    while (getline(N, K, ' ')) {
        cout << K << endl;
    }
    return 0;
}

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:

// C++ program to demonstrate
// anomaly of delimitation of
// getline() function
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string name;
    int id;
    // Taking id as input
    cout << "Enter your id: \n";
    cin >> id;
    // Takes the empty character as input
    cout << "Enter your name: \n";
    getline(cin, name);
    // Prints id
    cout << "Enter Your id : " << id << "\n";
    // Prints nothing in name field
    // as "\n" is considered a valid string
    cout << "Hi, " << name
         << " welcome to Tutorialandexample !\n";
    // Again Taking string as input
    getline(cin, name);
    cout << "Hi " << name
         << " welcome to Tutorialandexample !\n";
    return 0;
}

Output:

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

Related Topics

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Decimal to Hexadecimal in C++

We need to write a program in C++ that converts a decimal number into an equal hexadecimal number given a decimal value as input i.e. convert a number having a...

2 minutes read.

C++ Maximum Index Problem

Given an array A[] of positive integers. We will find the maximum of (j-i) such that i and j are the indexes of A[] and A[i] <= A[j], i<=j For...

5 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

4 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

goto statement in C and C++

goto statement in C and C++ The goto statement is a jump statement, also sometimes referred to as an unconditional jump statement. Within a function, the goto statement can be used...

3 minutes read.

C++ Bitset

Overview In C++, bitset represents a fixed-sequence of some bits values by either 0 and 1. Zero represents the value as false or unset, while 1 represents the value as true...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Timsort Implementation Using C++

Timsort Implementation Using C++ The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion...

3 minutes read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ this pointer

'this' is a pointer that points to the object for which this function was called. The 'this' pointer holds the memory address of the current object. The 'this' pointer is implicitly passed to...

2 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Divide by Zero Exception in C++

We use exception handling method to handle the divide by zero exception. Dividing a number with zero is generally mathematical error. We have to exception handling method to overcome this...

2 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.