C++常用的輸入函數總結

來源:互聯網
上載者:User

標籤:

主要的輸入輸出函數有6種:cin, cin.get() , cin.getline() ,getline()  , gets()  ,getchar()

cin

(1)根據變數的類型讀取資料

結束條件:斷行符號鍵、空格鍵、TAB

結束符的處理:緩衝區中丟棄使輸入結束的結束符(斷行符號鍵、空格鍵、TAB)

#include <iostream>using namespace std;void main(){    int a,b;    cin>>a>>b;    cout<<a+b<<endl;}

(2)接收字串

#include <iostream>using namespace std;void main(){    char ch[20];    cin>>ch;    cout<<ch<<endl;}

輸入:helloworld

輸出:helloworld

輸入:hello world(此時是空格鍵,表示輸入結束)

輸出:hello

cin.get()

(1)接收一個字元

結束條件:斷行符號鍵

結束符處理:緩衝區的Enter不丟棄

#include <iostream>using namespace std;void main(){    char ch;    //ch = cin.get();    cin.get(ch);    cout<<ch<<endl;}

輸入:he llo

輸出:h

(2)接收一行字串,cin.get(數組名,接收字元的數目), 

結束條件:Enter

結束符處理:緩衝區的Enter丟棄

#include <iostream>using namespace std;void main(){    char ch[20];    cin.get(ch,10);    cout<<ch<<endl;}

 

輸入:hello world

輸出:hello wor(9個字元加上‘/0‘)

cin.getline()

接收一個字串可以接受空格,

cin.getline(數組名,長度,結束符)  與 cin.get(數組名,長度,結束符)用法是一樣的

區別:當輸入的字串的長度超過指定的長度時,cin.getline()會出錯,cin不會執行。

而cin.get()繼續執行下次是從緩衝區內去字元

結束條件:Enter

結束符處理:丟棄Enter

#include <iostream>using namespace std;void main(){    char name[20];    char shcool[30];    cin.getline(name,10);    cin.getline(shcool,20);    cout<<"name:"<<name<<endl;    cout<<"shcool:"<<shcool<<endl;}

可以看到是上面的輸出的區別。

getLine()

接收字串,可以接受空格,是String流,注意標頭檔

#include <iostream>#include <string>using namespace std;int main (){    string str;    getline(cin,str);    cout<<str<<endl;}

gets()

#include <iostream>#include <string>using namespace std;int main (){    char ch[20];    gets(ch);    cout<<ch<<endl;}

getchar()

接收一個字元,是C語言的函數,

#include <iostream>#include <string>using namespace std;int main (){    char ch;    ch = getchar();    cout<<ch<<endl;}

 

C++常用的輸入函數總結

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.