C++言語ベースルーチン標準入力フロー

2887 ワード

賀先生の授業リンクこの授業の説明
例:個数不確定の成績を入力する
#include <iostream>
using namespace std;
int main( )
{
    float grade;
    cout<<"enter grade:";
    while(cin>>grade)//  cin     
    {
        if(grade>=85)
            cout<<grade<<" GOOD!"<<endl;
        if(grade<60)
            cout<<grade<<" fail!"<<endl;
        cout<<"enter grade:";
    }
    cout<<"The end."<<endl;
    return 0;
}

文字入力用のストリームメンバー関数-get関数
(1)パラメータなしget関数
#include <iostream>
using namespace std;
int main( )
{
    int c;
    cout<<"enter a sentence:"<<endl;
    while((c=cin.get())!=EOF)
        cout.put(c);
    return 0;
}

(2)パラメータがあるget関数
#include <iostream>
using namespace std;
int main( )
{
    char c;
    cout<<"enter a sentence:"<<endl;
    while(cin.get(c))  //            c,      ,cin.get(c)  
        cout.put(c);
    cout<<"end"<<endl;
    return 0;
}

(3)3つのパラメータを持つget関数
#include <iostream>
using namespace std;
int main( )
{
    char ch[20];
    cout<<"enter a sentence:"<<endl;
    cin.get(ch,10,'/');//  ‘/’       
    cout<<ch<<endl;
    return 0;
}

1行の文字を入力するストリームメンバー関数-getline関数
#include <iostream>
using namespace std;
int main( )
{
    char ch[20];
    cout<<"enter a sentence:"<<endl;
    cin>>ch;
    cout<<"The string read with cin is:"<<ch<<endl;
    cin.getline(ch,20,'/');// 19     '/'  
    cout<<"The second part is:"<<ch<<endl;
    cin.getline(ch,20);                              // 19     '/n'  
    cout<<"The third part is:"<<ch<<endl;
    return 0;
}

入力(ファイル)が終了したか否かを判断する――eof関数
#include <iostream>
using namespace std;
int main( )
{
    char c;
    while(!cin.eof( )) //eof( )            
        if((c=cin.get( ))!=' ')	//              
            cout.put(c);
    return 0;
}

ストリームのその他の関数を入力します.
#include <iostream>
using namespace std;
int main( )
{
    char c[20];
    int ch;
    cout<<"please enter a sentence:"<<endl;
    cin.getline(c,15,'/');
    cout<<"The first part is:"<<c<<endl;
    ch=cin.peek( );         //     
    cout<<"next character: "<<char(ch)<<endl;
    cin.putback(c[0]);   //  c[0]
    cin.getline(c,15,'/');
    cout<<"The second part is:"<<c<<endl;
    return 0;
}