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!
Input 1
Output
Seems ok right? Let's see another input example
Input 2
Output
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
Let's rewrite the same program but using the getline() function this time.
Input
Output
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.
Join Our Course

Offer ends in:
Days
Hours
Mins
Secs