getline()
In C++, the getline()
function converts user input into a character-delimited string and stores them in a variable. If a delimiting character is not specified, then the entire input will be stored.
Syntax
The getline()
function is defined in the <string>
header.
#include <string>
getline(cin, string, delim)
getline()
is part of the<string>
header, so it is included at the top of the file.cin
is the object in the stream, which would be the user input.string
refers to the variable the user input is set to.delim
refers to a character that the user’s input is stored up to.
Although not recommended in C++, since it deals with C strings, getline()
can be called on the cin
object as a member function like this:
cin.getline(string, length, delim)
length
is the expected size of the character array.
Example 1
#include <iostream>#include <string>using namespace std;int main() {string my_str;cout << "Enter a pet name: ";getline(cin, my_str);cout << "My pet's name is " + my_str + "!";}
This will output:
Enter a pet name:
If the user then inputs the string "Nimbus"
, this will be the final output:
My pet's name is Nimbus!
Example 2
In the example above, the user will be prompted to enter a pet name. Then, the getline()
function will take the input and set it to the my_str
variable. my_str
can then be used in the following operations.
The same example of getline()
, but called upon the cin
object, would look like this:
#include <iostream>using namespace std;int main() {char my_char_array[20];cout << "Enter a pet name: ";// Input: Nimbuscin.getline(my_char_array, 20);cout << "My pet's name is " << my_char_array << "!";// Output: My pet's name is Nimbus!}
Codebyte Example
Run the following codebyte to understand how the getline()
function works:
In the above example, using traditional cin >> myString
would result in only capturing the first word, “Codeacademy.” This is because cin >>
reads input until it encounters a space or newline. To read an entire line, including spaces and tabs, we use getline(cin, myString)
, which captures the full input line as a single string.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours