The C++ provides the getline()
function in order to read string input or a line from standard input. The getline() function is provided via the <string>
header or library. The getline() function reads provided characters from the standard input until the delimiting character
is encountered. The delimiting character is Enter
by default. Also, the size of the input can be specified as a fixed value for the getline() function.
getline() Function Syntax
istream& getline(istream& STREAM, string& STR, char DELIMETER);
- STREAM is the input stream where the data will be read. Its type is stream.
- STR is the string variable where the data will be stored.
- DELIMETER is used to parse the input. DELIMETER is optional.
Read Input with getline()
The getline() function is used to read standard input. The standard input is named as cin
in C++. We will also create the string named str
in order to store read input.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Name: \n";
getline(cin, str);
cout << "Hello, " << str;
return 0;
}
Split According To Delimiter
The input can be split according to the specified delimiter. The delimiter is provided as 3rd parameter to the getline() function. In the following example, we will split the input with a space delimiter.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Name: \n";
getline(cin, str, ' ');
cout << "Hello, " << str;
return 0;
}