c++面向行的輸入getline()和get()

來源:互聯網
上載者:User

標籤:add   數字   std   就是   lin   line   etl   ddr   指定   

來源:c++ primer plus

在c++裡當我們輸入一個字串時習慣用cin,但是cin只能讀取一段不含空格的字串,如果我們需要讀取一段包含空格的字串時,就需要用到getline()或get()。下面介紹getline()和get(),這兩個都是讀取到分行符號結束。

1.getline():

假設現在我們要輸入一個名字,儲存在name數組裡:

#include<iostream>
using namespace std;
int main()
{
  char name[10];
  cin.getline(name,10);
  cout<<name<<endl;
  return 0;
}
//第一次輸入:123456    第一次輸出:123456
//第二次輸入:1234567890 第二次輸出:123456789

調用方式是cin.getline(),裡面有兩個參數,分別是數組名和數組長度,在這裡要注意的是如果長度是10,那麼最多隻會讀取9個字元,因為還有一個位置要留給Null 字元‘\0‘,如果只輸入5個,那麼剩餘的都會用Null 字元來補滿。對於getline(),它一直讀取到遇到分行符號或到達指定數目字元時結束,然後分行符號會被丟棄,不留在輸入隊列裡(這是接下來它和get()的細微區別)。

getline()也可以這樣用:

#include<iostream>using namespace std;int main(){    char name1[10],name2[10];    cin.getline(name1,10).getline(name2,10);
  //第一次調用返回一個cin對象,然後這個對象再調用getline() cout<<name1<<‘ ‘<<name2<<endl; return 0;}/*輸入:123 456輸出:123 456 */

2.get():

get()和getline()很像,也是兩個參數,但是get()讀取到分行符號停止時,分行符號會留在輸入隊列裡,下一次讀取時就會再次讀取到分行符號,導致讀取為空白。

例如:

#include<iostream>using namespace std;int main(){    char name1[10],name2[10];    cin.get(name1,10);    cin.get(name2,10);    cout<<name1<<‘ ‘<<name2<<endl;    return 0;}/*輸入:123輸出:123 */

在這裡我是想輸入123再輸入456的,但是我沒機會了,因為輸入123時遇到分行符號然後停止,第二次調用時這個分行符號還在輸入隊列裡,程式就會再次停止,後面就讀取不到內容了。

當cin.get()裡面沒用參數時,它會吸取一個字元,包括分行符號,所以我們可以這樣:

#include<iostream>using namespace std;int main(){    char name1[10],name2[10];    cin.get(name1,10);    cin.get();    cin.get(name2,10);    cout<<name1<<‘ ‘<<name2<<endl;    return 0;}/*輸入:123456輸出:123 456  */

也可以這樣寫:

#include<iostream>using namespace std;int main(){    char name1[10],name2[10];    cin.get(name1,10).get();    cin.get(name2,10);    cout<<name1<<‘ ‘<<name2<<endl;    return 0;}/*輸入:123456輸出:123 456  */

 空行和超出分配空間都會導致出錯,應該盡量避免。

還有就是當我們在實際運用中可能要數字和字串混合輸入,這個時候容易出錯,舉一個書上的例子:

#include<iostream>using namespace std;int main(){    int year;    char address[20];    cin>>year;    cin.getline(address,20);    cout<<year<<endl;    cout<<address<<endl;    return 0;}/*輸入輸出: 20182018*/

我們輸入了年份,這個時候分行符號還在輸入隊列裡,然後調用getline()時遇到分行符號,直接結束讀取。。。,這裡可以用cin.get()來吸收分行符號。

差不多就這麼多吧。

c++面向行的輸入getline()和get()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.