Skip to main content

Strings

Taking Input in Strings

So far we have used cin to take inputs in C++ but can we take a string input in the same way?

Let's see!

#include <iostream>
using namespace std;
 
int main() {
 
    string name;
  
    cout << "Enter your name: ";
    cin >> name;
 
    cout << "Your name is " << name;
 
    return 0;
}

Input 1

William

Output

William

Seems ok right? Let's see another input example

Input 2

William Shakespeare

Output

William

William Shakespeare is a valid string but why isn't it printed correctly? It's because cin object reads string only till a space is encountered. Hence, it gave the desired output in the first case but failed in the second case.

Let's see how can we overcome this problem and take the entire string as an input.

'getline()' function

Instead of using cin, we have another function known as getline() function to take string inputs especially for full lines.

Syntax

getline(cin, string_variable);

Let's rewrite the same program but using the getline() function this time.

#include <iostream>
using namespace std;
 
int main() {
 
    string name;
  
    cout << "Enter your name: ";
    getline(cin, name);
 
    cout << "Your name is " << name;
 
    return 0;
}

Input

William Shakespeare

Output

William Shakespeare

Hence, getline() function enables us to take an entire line as an input for a string.


Quiz

What will be the values of the standard and subject variables if the inputs are 12 Science and Physics Chemistry Maths respectively.

string standard;
string subjects;
getline(cin, standard);
cin >> subjects;