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个字符,如果遇到换行符‘\n’(第一种形式)或delim(第二种形式),则读取终止,’\n’或delim都不会被保存进s对应的数组中。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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 <<  "!\n" ;
 
   return  0;
}

猜你喜欢

转载自blog.csdn.net/qq_22070551/article/details/81222723