C++中的getline()

C++中本质上有两种getline函数,一种在头文件<istream>中,是istream类的成员函数。一种在头文件<string>中,是普通函数。

在<istream>中的getline函数有两种重载形式:

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

作用是从istream中读取至多n个字符保存在s对应的数组中。即使还没读够n个字符,如果遇到换行符' '(第一种形式)或delim(第二种形式),则读取终止,' '或delim都不会被保存进s对应的数组中。

样例程序(摘自cplusplus.com):

// istream::getline example
#include <iostream>     // std::cin, std::cout
 
int main () {
  char name[256], title[256];
 
  std::cout << "Please, enter your name: ";
  std::cin.getline (name,256);
 
  std::cout << "Please, enter your favourite movie: ";
  std::cin.getline (title,256);
 
  std::cout << name << "'s favourite movie is " << title;
 
  return 0;
}

  

在<string>中的getline函数有四种重载形式:

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);
用法和上一种类似,不过要读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。

样例程序(摘自cplusplus.com):

// extract to string
#include <iostream>
#include <string>
 
int main ()
{
  std::string name;
 
  std::cout << "Please, enter your full name: ";
  std::getline (std::cin,name);
  std::cout << "Hello, " << name << "!
";
 
  return 0;
}
原文地址:https://www.cnblogs.com/la0bei/p/5741631.html