欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C++中g(shù)etline()的用法詳解

 更新時間:2020年02月13日 11:03:05   作者:學無止境~zZ  
這篇文章主要介紹了C++中g(shù)etline()的用法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

getline()用法

getline是C++標準庫函數(shù);它有兩種形式,一種是頭文件< istream >中輸入流成員函數(shù);一種在頭文件< string >中普通函數(shù);

它遇到以下情況發(fā)生會導致生成的本字符串結(jié)束:
(1)到文件結(jié)束,(2)遇到函數(shù)的定界符,(3)輸入達到最大限度。

輸入流成員函數(shù)getline()

函數(shù)語法結(jié)構(gòu):

在< istream >中的getline()函數(shù)有兩種重載形式:

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

作用是: 從istream中讀取至多n個字符(包含結(jié)束標記符)保存在s對應的數(shù)組中。即使還沒讀夠n個字符,
如果遇到delim 或 字數(shù)達到限制,則讀取終止,delim都不會被保存進s對應的數(shù)組中。

代碼實例

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

普通函數(shù)getline()

函數(shù)語法結(jié)構(gòu):

在< string >中的getline函數(shù)有四種重載形式:

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);

函數(shù)的變量:

is :表示一個輸入流,例如 cin。
str :string類型的引用,用來存儲輸入流中的流信息。
delim :char類型的變量,所設(shè)置的截斷字符;在不自定義設(shè)置的情況下,遇到'\n',則終止輸入

用法和上一種類似,但是讀取的istream是作為參數(shù)is傳進函數(shù)的。讀取的字符串保存在string類型的str中。
代碼實例

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論