Getline in C++ – cin getline() Function Example
Ihechikara Vincent Abba

In this article, we’ll talk about the getline() function in C++. This is an inbuilt function that accepts single and multiple character inputs.
When working with user input in C++, the cin object allows us to get input information from the user. But when we try to log out the user’s input that has multiple values, it only returns the first character.
This happens because the C++ compiler assumes that any white space terminates the program when getting the input. That is, «My name is Ihechikara» would only return «My» when logged out.
Here is a better example:
In the code above, the user is asked to input their bio. They went on to input «JavaScript is my favorite language». But when the bio was logged to the console, only «JavaScript» was logged out.
Next, we’ll see how to use the getline() function to get the rest of the characters in the string.
C++ getline() Function Example
In this section, we’ll see a practical example of using the getline() function.
In the example above, we passed in two parameters in the getline() function: getline(cin, bio); . The first parameter is the cin object while the second is the bio string variable.
When you run the code, you’ll be prompted to input some text. After you’ve done that, hit enter and see the output that has all the text from your input instead of just the first character.
In my case, I typed in a string with multiple characters and got it logged out to the console. Go on and try it to see how it works.
With this, you can work effectively with user inputs in your programs.
Conclusion
In this article, we talked about the getline() function which enables us get multiple characters from a user’s input.
We first saw what happens when we get a string with multiple characters from a user – only the first character is returned.
We then saw how to get all the characters from the string using the getline() function which takes two parameters – the cin object and the string variable.
std::cin.getline( ) vs. std::cin
When should std::cin.getline() be used? What does it differ from std::cin ?
![]()
5 Answers 5
Let’s take std::cin.getline() apart. First, there’s std:: . This is the namespace in which the standard library lives. It has hundreds of types, functions and objects.
std::cin is such an object. It’s the standard character input object, defined in <iostream> . It has some methods of its own, but you can also use it with many free functions. Most of these methods and functions are ways to get one or more characters from the standard input.
Finally, .getline() is one such method of std::cin (and other similar objects). You tell it how many characters it should get from the object on its left side ( std::cin here), and where to put those characters. The precise number of characters can vary: .getline() will stop in three cases: 1. The end of a line is reached 2. There are no characters left in the input (doesn’t happen normally on std::cin as you can keep typing) 3. The maximum number of characters is read.
getline
Функция getline предназначена для ввода данных из потока, например, для ввода данных из консольного окна. Если формально описывать ее функционал, то она извлекает данные из входного потока до строкового разделителя, который не записывается в получившийся массив данных.
В итоге, получается извлечение одной строки и записывание ее в переменную. Сама конструкция getline выглядит так:
где string – переменная типа char*, в которую запишется строка, streamsize — максимально количество символов, которое может быть записано в строку, и separator – строковый разделитель, показывающий на конец строки. Последний параметр функции можно опустить, тогда будет задан сепаратор по умолчанию — ‘\n’. Приведем пример работы функции getline в программе:
Для начала нужно подключить соответствующую библиотеку iostream для работы с потоками ввода/вывода. Программа записывает 2 предложения, предложение является законченным, только если в конце стоит ’;’ или такой символ не стоит, но длина предложения 256 символов. В функции в качестве потока поставлен вывод с экрана cin, запись идет в str и разделителем является ’;’. После записи предложения выводятся на экран.
Функция getline с типом string
У функции getline есть ещё один популярный вариант, использующий строковый тип неограниченной длины string
How to use std::getline() in C++?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In this article, we’ll take a look at using the function std::getline() in C++. This is a very handy function if you want to read characters from an input stream.
Let’s find out how we can use this properly, using some illustrative examples.
Basic Syntax of std::getline() in C++
This function reads characters from an input stream and puts them onto a string.
We need to import the header file <string> , since getline() is a part of this file.
While this takes template arguments, we’ll focus on string inputs (characters) , since the output is written to a string.
What this says is that getline() takes an input stream, and writes it to output . Delimiters can be optionally specified using delim .
This also returns a reference to the same input stream, but for most cases, we don’t need this handle.
Using std::getline() to read from input streams
Now that we know the basic syntax, let’s get input from std::cin (standard input stream) to a string.
Output
Indeed, we were able to get the input from std::cin without any problems!
Let’s now take another example, where we have a file input.txt containing the following content:
Let’s now read the file line by line and store them into a vector of strings!
The core logic will be to keep reading using std::getline(file) until the input stream reaches EOF.
We can easily write this using this format:
The complete code is shown below:
Output
Using std::getline() in C++ to split the input using delimiters
We can also use the delim argument to make the getline function split the input in terms of a delimiter character.
By default, the delimiter is \n (newline). We can change this to make getline() split the input based on other characters too!
Let’s set the delim character to a space ’ ’ character to the above example and see what happens!
Output
Indeed, we have our space separated string now!
Potential Issues with using std::getline()
While std::getline() is a very useful function, there could be some problems that you may face when using it along with some input streams such as std::cin .
- std::getline() does not ignore any leading white-space / newline characters.
Because of this, if you call std::cin >> var; just before getline() , there will be a newline still remaining in the input stream, after reading the input variable.
So, if you call getline() immediately after cin , you will get a newline instead, since it is the first character in the input stream!
To avoid this, simply add a dummy std::getline() to consume this new-line character!
The below program shows an issue with using cin just before getline() .
Output
Notice that I wasn’t able to enter the name at all! Since a trailing newline was there in the input stream, it simply took that, and since it is a delimiter, it stopped reading!
Now let’s add a dummy std::getline() call just before our actual std::getline() .
Output
We’ve finally fixed our bug! This hopefully makes you think a bit more before blindly using std::getline() .
Unfortunately, there are no elegant methods to get input in C++, so we must make do with what we have!
Conclusion
In this article, we learned about using std::getline() in C++. We also look at some examples which illustrate the power, and pitfalls of this function.
References
-
std::getline() on using std::getline()
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.