C++中,getline函式的詳解
阿新 • • 發佈:2018-11-24
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;
}
|