Getline in C++
To read an expression or an entire line through a data stream, use the standard library method getline() in C++. This function is included in the library. When the defining letter is met, the getline() function adds letters to the string variable by pulling them from its input flow. In the process, if a string is provided, it will replace the already stored information in the character string object str.
There are two syntax to use the getline() method in C++:
Syntax 1:
Istream getline(istream& is,
string& str, char delim);
Parameters:
- Is: It specifies about the data stream from which to read input and is a component of the istream class.
- Str: This parameter is a string object where the input data has been extracted from the stream, it is saved there.
- delim: The following character serves as a delimiter, informing the function how to stop processing inputs once it reaches it.
Programs to show how the getline() function uses a delimiter.
Example Code 1:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define MAXIMUM_NAME_LENGTH 60
#define MAXIMUM_LOCATION_LENGTH 120
#define MAXIMUM_ABOUT_LENGTH 250
int main () {
char y_name[MAXIMUM_NAME_LENGTH], y_location[MAXIMUM_LOCATION_LENGTH], about_y[MAXIMUM_ABOUT_LENGTH];
cout << "Enter your name: ";
cin.getline (y_name, MAXIMUM_NAME_LENGTH);
cout << "Enter your Place: ";
cin.getline (y_location, MAXIMUM_LOCATION_LENGTH);
cout << "Enter your job (press # to complete): ";
cin.getline (about_y, MAXIMUM_ABOUT_LENGTH, '#');
cout << "\nEntered details are:\n"<<'\n';
cout << "Name: " << y_name << endl;
cout << "location: " << y_location << endl;
cout << "Profession is: " << about_y << endl;
}
Output:
![Getline in C++](https://static.tutorialandexample.com/cpp/getline-in-cpp1.png)
This program will halt and terminate if you exceed the defined limitation in the previous instance, especially when using the #define MAX_NAME_LEN 6 macro. This applies to all macros used with the getline() method.
Example Code 2:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define MAXIMUM_NAME_LENGTH 6
#define MAXIMUM_LOCATION_LENGTH 120
#define MAXIMUM_ABOUT_LENGTH 250
int main () {
char y_name[MAXIMUM_NAME_LENGTH], y_location[MAXIMUM_LOCATION_LENGTH], about_y[MAXIMUM_ABOUT_LENGTH];
cout << "Enter your name: ";
cin.getline (y_name, MAXIMUM_NAME_LENGTH);
cout << "Enter your city: ";
cin.getline (y_location, MAXIMUM_LOCATION_LENGTH);
cout << "Enter your job (press # to complete): ";
cin.getline (about_y, MAXIMUM_ABOUT_LENGTH, '#');
cout << "\n\nEntered details are:\n\n";
cout << "Name: " << y_name << endl;
cout << "location: " << y_location << endl;
cout << "job is: " << about_y << endl;
}
Output:
It makes sense in this case since the name of the field's length exceeded the specified limit; as a result, the application terminated and stopped running.
Syntax 2
getline (istream& is, string& str); istream&
The first and second declarations are nearly identical. Both have a separation letter (newline(\n) by default), and that's the sole difference.
Parameters:
- Is: It informs the function in question about the data stream from which it reads input that is a member of the istream type.
- Str: The object in question is a string; whenever the input has been extracted from the road, it is saved there.
Example Code 1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "enter your name: \n";
getline(cin, str);
cout << "hi, " << str
<< " how are you !\n";
return 0;
}
Output:
![Getline in C++](https://static.tutorialandexample.com/cpp/getline-in-cpp3.png)
Example Code 2:
#include <bits/stdc++.h>
using namespace std;
int main()
{
string N, M;
getline(cin, N);
stringstream X(N);
while (getline(X, M, ' ')) {
cout << N << endl;
}
return 0;
}
Output:
![Getline in C++](https://static.tutorialandexample.com/cpp/getline-in-cpp4.png)
A new line, or ('\n'), character is seen by this algorithm as the separation character, and it is a valid input.
Below is an illustration of how a new line can result in an issue:
Example Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name;
int id;
cout << "Please enter your id: \n";
cin >> id;
cout << "Please enter your name: \n";
getline(cin, name);
cout << "Your id : " << id << "\n";
cout << "Hello, " << name
<< " welcome to GfG !\n";
getline(cin, name);
cout << "Hello, " << name
<< " welcome to GfG !\n";
return 0;
}
Output:
![Getline in C++](https://static.tutorialandexample.com/cpp/getline-in-cpp5.png)
Applications of C++ getline method:
There are numerous uses for the C++ getline operation, including
- Receiving data entered into the conventional input stream (cin): To obtain a whole line of text form the standardized input the road, use the getline function in C++. This is particularly helpful for receiving keystrokes from users.
- Reading information within a file: Just a single line at a moment, written information can be retrieved form a file using the C++ getline method. Handling huge files piece by piece while needing to load every line onto storage simultaneously is made possible by this.
- Parsing strings: You may obtain specific information from a string of characters using the C++ getline function. For instance, you might retrieve particular information from a value separated by comma file using the C++ getline method.
- Text data computation: Getline is capable of handling text data through documents, strings, and user input, among other types of data. For instance, you may parse plain text via a relational database or retrieve the contents of a log file using the C++ getline method.
- Manipulation of strings: getline reads each section of text & performs any needed treatment on these. To retrieve particular phrases or words off a string and save them to a different data framework, for instance, you may use the getline function.
The C++ getline method is a flexible method that may be applied in various scenarios to analyze and work with text input.
Benefits of Using C++'s Getline Function:
- Unlike cin alone, the c++ Std::getline function can read an entire line of text containing blanks.
- It's not limited to cin; it can handle any kind of input line.
- By setting the highest word count to be read, overflowing buffer problems may be avoided.
- Any text document with characters isolated by a certain delimiter, such as CSV files, can be parsed using it.
- A character collection may be more difficult to start with than a std::string, but you can convert an entire line of information into one using the std::getline method in C++.
Drawbacks of Using C++'s Getline Function:
Because it analyzes the complete line of text, it may read just one value more slowly than Cin.
This means that you might need to employ further functions for obtaining specific information from the data provided because you can't define the delimiter that is employed for dividing each value.
- Leading blank elements are not immediately skipped by the C++ std::getline function; users may have to explicitly write software that handles this.
- If your input includes characters longer compared to the designated minimum length, unforeseen outcomes may result.
- Because it accepts the information as textual and might add unanticipated symbols or alter the format of the information, it might not be the ideal option for processing binary information.