C++ getline of

  • 2020-07-21 09:29:08
  • OfStack

The usage getline ()

getline is C++ standard library function; It comes in two forms, one is a header file < istream > Input stream member function; 1 in the header file < string > Medium ordinary function;

It terminates the generated string when it encounters the following:
(1) At the end of the file, (2) the delimiter of the function is encountered, and (3) the input is maximized.

Input stream member function getline()

Function syntax structure:

in < istream > The getline() function in


istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );

Effect: Reads up to n characters from istream, including the closing tag, and stores them in the array corresponding to s. Even if you haven't read n enough,
If delim is encountered or the word limit is reached, the read terminates and delim is not saved into the array corresponding to s.

The code examples


#include <iostream>   
using namespace std;

int main()
{
 char name[256];
 cout << "Please input your name: ";
 cin.getline(name, 256);
 cout << "The result is:  " << name << endl;
 
 return 0;

}


#include <iostream>
using namespace std;

int main( )
{
  char line[100];
  cout << " Type a line terminated by 't'" << endl;
  cin.getline( line, 100, 't' );
  cout << line << endl;
  
  return 0;
}

Ordinary function getline()

Function syntax structure:

in < string > There are four overloaded forms of getline function in


istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);

Variables of the function:

is: Represents 1 input stream, such as cin.
str: A reference of type string used to store flow information in an input stream.
delim: variable of type char, with truncated character set; If '\n' is encountered without custom Settings, the input is terminated

The usage is similar to the previous one, but istream is read into the function as the argument is. The read string is stored in str of type string.
The code examples


#include <iostream>
#include <string>
using namespace std;

int main()
{
 string name;
 cout << "Please input your name: ";
 getline(cin, name);
 cout << "Welcome to here!" << name << endl;
 
 return 0;

}


#include <iostream>
#include <string>
using namespace std;

int main()
{
 string name;
 cout << "Please input your name: ";
 getline(std::cin, name, '#');
 cout << "Welcome to here!" << name << endl;
 
 return 0;
}


Related articles: