C++ getline()的兩種用法

getline():用於讀入一整行的數據。在C++中,有兩種getline函數。第一種定義在頭文件<istream>中,是istream類的成員函數;第二種定義在頭文件<string>中,是普通函數。ios

第一種: 在<istream>中的getline()函數有兩種重載形式:數組

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

做用是: 從istream中讀取至多n個字符(包含結束標記符)保存在s對應的數組中。即便還沒讀夠n個字符,若是遇到delim標識符或字數達到限制,則讀取終止。delim標識符會被讀取,可是不會被保存進s對應的數組中。注意,delim標識符在指定最大字符數n的時候纔有效。函數

#include <iostream>
using namespace std;

int main()
{
    char name[256], wolds[256];
    cout<<"Input your name: ";
    cin.getline(name,256);
    cout<<name<<endl;
    cout<<"Input your wolds: ";
    cin.getline(wolds,256,',');
    cout<<wolds<<endl;
    cin.getline(wolds,256,',');
    cout<<wolds<<endl;
    return 0;
}

輸入spa

Kevin
Hi,Kevin,morning

輸出code

Kevin
Hi
Kevin

第二種: 在<string>中的getline函數有四種重載形式:blog

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中。ci

is:表示一個輸入流,例如cin。字符串

str:string類型的引用,用來存儲輸入流中的流信息。get

delim:char類型的變量,所設置的截斷字符;在不自定義設置的狀況下,遇到’\n’,則終止輸入。string

#include<iostream>
#include<string>
using namespace std;
int main(){
    string str;
    getline(cin, str, 'A');
    cout<<"The string we have gotten is :"<<str<<'.'<<endl;
    getline(cin, str, 'B');
    cout<<"The string we have gotten is :"<<str<<'.'<<endl;
return 0;}

輸入

i_am_A_student_from_Beijing

輸出

The string we have gotten is :i_am_.
The string we have gotten is :_student_from_.
相關文章
相關標籤/搜索