Skip to content

[Edit] C++ User Input: getline() #6695

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 14, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
120 changes: 82 additions & 38 deletions content/cpp/concepts/user-input/terms/getline/getline.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,41 +5,46 @@ Subjects:
- 'Computer Science'
- 'Game Development'
Tags:
- 'Functions'
- 'Strings'
- 'Characters'
- 'Data Types'
- 'Functions'
- 'Strings'
CatalogContent:
- 'learn-c-plus-plus'
- 'paths/computer-science'
---

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.
In C++, the **`getline()`** [function](https://www.codecademy.com/resources/docs/cpp/functions) converts user input into a character-delimited [string](https://www.codecademy.com/resources/docs/cpp/strings) and stores it into a [variable](https://www.codecademy.com/resources/docs/cpp/variables). If a delimiting character is not specified, then the input is stored until `\n` (newline) is encountered. This function is widely used in reading multi-word user input, processing lines from text [files](https://www.codecademy.com/resources/docs/cpp/files), and parsing structured data such as CSV records or configuration files where input must be read line-by-line.

## Syntax

The `getline()` function is defined in the `<string>` header.
The `getline()` function is defined in the `<string>` header:

```pseudo
#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.
**Parameters:**

- `cin`: The [object](https://www.codecademy.com/resources/docs/cpp/objects) in the stream, which would be the user input.
- `string`: Refers to the variable to which the user input is set.
- `delim` (Optional): Refers to a character the user input is stored up to.

Although not recommended in C++, since it deals with [C strings](https://www.codecademy.com/resources/docs/c/strings), `getline()` can be called on the `cin` object as a member function like this:

```pseudo
cin.getline(string, length, delim)
```

- `length` is the expected size of the character array.
**Parameters:**

- `string`: Refers to the variable to which the user input is set.
- `length`: The maximum number of characters to read, including the null terminator.
- `delim` (Optional): Refers to a character the user input is stored up to.

## Example 1: Using `getline()` Without `delim`

## Example 1
This example demonstrates the usage of the `getline()` function without the `delim` parameter:

```cpp
#include <iostream>
Expand All @@ -48,70 +53,109 @@ cin.getline(string, length, delim)
using namespace std;

int main() {
// Create a string
string my_str;

// Take input from the user
cout << "Enter a pet name: ";

// Store the input in the string
getline(cin, my_str);

cout << "My pet's name is " + my_str + "!";
}
```

This will output:

```shell
Enter a pet name:
```

If the user then inputs the string `"Nimbus"`, this will be the final output:
Here is the output if the user input is "Nimbus":

```shell
Enter a pet name: Nimbus
My pet's name is Nimbus!
```

## Example 2
## Example 2: Using `getline()` with `delim`

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:
This example demonstrates the usage of the `getline()` function with the `delim` parameter:

```cpp
#include <iostream>
#include <string>

using namespace std;

int main() {
char my_char_array[20];
// Create a string
string my_str;

// Take input from the user
cout << "Enter a pet name: ";
// Input: Nimbus
cin.getline(my_char_array, 20);

cout << "My pet's name is " << my_char_array << "!";
// Output: My pet's name is Nimbus!
// Store the input in the string until '\n' (newline) is encountered
getline(cin, my_str, '\n');

cout << "My pet's name is " + my_str + "!";
}
```

## Codebyte Example
Here is the output if the user input is "Dora":

Run the following codebyte to understand how the `getline()` function works:
```shell
Enter a pet name: Dora
My pet's name is Dora!
```

## Codebyte Example: Using `getline()` on `cin`

This codebyte example applies the `getline()` function on the `cin` object:

```codebyte/cpp
#include <iostream>
#include <string>

using namespace std;

int main() {
string myString;
// Create a string
char my_char_array[20];

cout << "Enter your input: \n";
// Input: Codeacademy is awesome
getline(cin, myString);
// Take input from the user
cout << "Enter a pet name: ";

// Store the input in the string until the character limit (20) is reached
cin.getline(my_char_array, 20);

cout << myString << "!";
// Output: Codeacademy is awesome!
cout << "My pet's name is " << my_char_array << "!";
}
```

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.
## `getline()` vs `cin`

| Feature | `getline()` | `cin` |
| ---------------------------- | ----------------------------------- | ---------------------------------------- |
| Reads input until | Newline (`\n`) | Whitespace (space, tab, newline) |
| Captures spaces | Yes | No |
| Input type | Entire line as `std::string` | Word/token as `std::string`, `int`, etc. |
| Common use cases | Full names, sentences, file lines | Single words, numbers, basic input |
| Header required | `<string>` and `<iostream>` | `<iostream>` |
| Works with file streams | Yes | Yes |
| Buffer issues with mixing | Must use `cin.ignore()` after `cin` | Not affected when used alone |
| Ease of parsing line-by-line | Excellent | Limited |

## Frequently Asked Questions

### 1. Can `getline()` read input from files?

Yes, `getline()` works with any input stream, including file streams (`std::ifstream`).

### 2. Does `getline()` include the newline character (`\n`) in the string?

No, `getline()` stops reading at the newline but does not store it in the string. The result is a clean line without the `\n`.

### 3. Can I use a custom delimiter with `getline()`?

Yes, you can specify a delimiter:

```cpp
std::getline(std::cin, str, ';'); // Stops at semicolon instead of newline
```

This is useful for parsing CSV or semi-colon-separated input.