Reading String From Input in C++

In this article, we will discuss different ways to read strings from input in C++. The cin object and getline function can be used to read strings.

Using the cin to read string input

In this example, we will use cin object to read strings. The cin is an istream object.

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter your name: ";

    string name;
    cin>> name;

    cout << "Hello " << name <<"!"<<endl;

    return 0;
}

Output

Please enter your name: Tom
Hello Tom!

Note that there is no explicit memory management and no fixed-size buffer to overflow.

Using the getline to read string

Let’s use getline function to read string input.

//Get line from stream into string
istream& getline (istream& is, string& str);

is : the istream object from which characters are extracted.

str : string object where the extracted line is stored.

Let’s look into an example.

#include <iostream>

using namespace std;

int main()
{
    cout << "Please enter your name: ";

    string name;
    getline(cin,name);

    cout << "Hello " << name <<"!"<<endl;

    return 0;
}

Output

Please enter your name: Bob
Hello Bob!

Leave a Comment