getline()的使用


一:istream類的公共成員函數getline()

  1.函數入口形式為:(1.1)istream& getline(char *s,stream_size n);

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

  2.函數功能為:

                函數(1.1)功能為取輸入流字符,並以字符串形式存貯於s所指空間,直到讀取了n-1個字符或者讀到‘\n’字符為止

          (讀取字符中不包括‘\n’但是,程序會在s空間末尾加上‘\n’,就相當於讀取了‘\n’),函數返回值為輸入流引用類型即,

           當前輸入流的引用。           

                函數(1.2)功能為取輸入流字符,並以字符串形式存貯於s所指空間,直到讀到了,字符delim(單不讀取delim)

           或者n-1個字符或者讀到‘\n’字符為止(讀取字符中不包括‘\n’但是,程序會在s空間末尾加上‘\n’,就相當於讀取了‘\n’),

           函數返回值為輸入流引用類型即,當前輸入流的引用。 

    3.舉例:

 

#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;
}

 

輸入名字:Jonathan 輸入電影名:《up in the air》

輸出: Jonathan's favourite movie is 《up in the air》

二: 頭文件<string>定義函數getline()

  1.函數入口形式為:(2.1)istream& getline(istream& in,string& str,char delim);

             (2.2)istream& getline(istream& in,string& str);

  2功能描述:Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).

  3舉例:

// 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;
}

參考:http://www.cplusplus.com/reference/istream/istream/getline/

   http://www.cplusplus.com/reference/string/string/getline/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM