C++ cin.getline及getline()用法詳解
下面先看下C++ cin.getline用法,具體內容如下所示:
使用 C++ 字元陣列與使用 string 物件還有另一種不同的方式,就是在處理它們時必須使用不同的函式集。例如,要讀取一行輸入,必須使用 cin.getline 而不是 getline 函式。這兩個的名字看起來很像,但它們是兩個不同的函式,不可互換。
與 getline 一樣,cin.getline 允許讀取包含空格的字串。它將繼續讀取,直到它讀取至最大指定的字元數,或直到按下了回車鍵。以下是其用法示例:
cin.getline(sentence,20);
getline 函式使用兩個用逗號分隔的引數。第一個引數是要儲存字串的陣列的名稱。第二個引數是陣列的大小。當 cin.getline 語句執行時,cin 讀取的字元數將比該數字少一個,為 null 終止符留出空間。這樣就不需要使用 setw 操作符或 width 函式。以上語句最多可讀取 19 個字元,null 終止符將自動放在陣列最後一個字元的後面。
下面的程式演示了 getline 函式的用法,它最多可以讀取 80 個字元:
// This program demonstrates cinT s getline function // to read a line of text into a C-string. #include <iostream>、 using namespace std; int main() { const int SIZE = 81; char sentence[SIZE]; cout << "Enter a sentence: "; cin.getline (sentence,SIZE); cout << "You entered " << sentence << endl; return 0; }
程式輸出結果:
Enter a sentence: To be,or not to be,that is the question.
You entered To be,that is the question.
補充:C++ getline()的兩種用法
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個字元,如果遇到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,'); cout<<wolds<<endl; return 0; }
輸入
Kevin
Hi,Kevin,morning
輸出
Kevin
Hi
Kevin
第二種: 在<string>中的getline函式有四種過載形式:
istream& getline (istream& is,string& str,char delim); istream& getline (istream&& is,char delim); istream& getline (istream& is,string& str); istream& getline (istream&& is,string& str);
用法和上第一種類似,但是讀取的istream是作為引數is傳進函式的。讀取的字串儲存在string型別的str中。
is:表示一個輸入流,例如cin。
str:string型別的引用,用來儲存輸入流中的流資訊。
delim:char型別的變數,所設定的截斷字元;在不自定義設定的情況下,遇到'\n',則終止輸入。
#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,'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_.
總結
以上所述是小編給大家介紹的C++ cin.getline及getline()用法詳解,希望對大家有所幫助,也非常感謝大家對我們網站的支援!