字符串輸入函數cin.getline()、與cin.get()的區別

//字符串輸入函數cin.getline()、與cin.get()的區別
#include <iostream>
using namespace std;
int main()
{
    char ch0[10];
    char ch1[10];
    char ch2[10];
    char ch3;
   
    /*
     * getline()函數讀取整行,它使用經過回車鍵輸入的換行符來肯定輸入結尾。
     * 隨後getline()將丟棄換行符,即清除輸入隊列中的換行符。
     */   
    cout<<"please input string0:"<<endl;
    cin.getline(ch0,10);
    cout<<"please input string1:"<<endl;
    cin.getline(ch1,10);
    cout<<"result from getline:"<<endl;
    cout<<ch0<<endl
        <<ch1<<endl
        <<endl;ios


    /*
     * 工做方式與getline()類似。不一樣之處在於get()函數不會丟棄輸入隊列中的
     * 換行符,而是將其保留在輸入隊列中。
     *
     * 若是不借助幫助,get()將不能跨過換行符,即後面的輸入將沒法正常進行。
     */
    cout<<"please input string0:"<<endl;
    cin.get(ch0,10);
    ch3 = cin.get();        //不帶參數的get()能夠接收任何ascii碼(即便是換
                            //行符)
    cout<<"please input string1:"<<endl;
    cin.get(ch1,10);
    cout<<"please input string2:"<<endl;
    cin.getline(ch2,10);    //利用getline()函數也能夠清楚輸入隊列中的換行
                            //符
    cin.get(ch2,10);
    cout<<"result from get:"<<endl;
    cout<<ch0<<endl
        <<ch1<<endl
        <<ch2<<endl
        <<(int)ch3<<endl;   //可見上面不帶參數的get()函數接收了換行符(換行
                            //符的ascii碼值爲10)
}函數

image

相關文章
相關標籤/搜索