Translations of this page?:

構文:

#include <string>
istream& std::getline( istream& is, string& s );
istream& std::getline( istream& is, string& s, charT delimiter );

C++の string ヘッダには(stringのメンバ関数ではない)グローバル関数 getline() が定義されている. これは入力ストリーム is から1行を読み込み文字列 s にセットする. デリミタが指定されている場合はそれを終端として利用する.指定されない場合は二つ目の定義を以下のように呼び出す.

return getline( is, s, is.widen( '\n' ) );

注: 入力ストリームは文字の型Charに対応したbasic_istream<charT>型.

次の例は標準入力から一行読み込みそれを標準出力に表示する.

string s;
getline( cin, s );
cout << "You entered " << s << endl;

行を取り出した後,それを加工するには stringstreams が利用できる. 次の例は標準入力から数字を読み込むが,ダブルスラッシュではじまる行はコメントとして無視する.

// expects either space-delimited numbers or lines that start with
// two forward slashes (//)
string s;
while( getline(cin,s) ) {
  if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) {
    cout << "  ignoring comment: " << s << endl;
  } else {
    istringstream ss(s);
    double d;
    while( ss >> d ) {
      cout << "  got a number: " << d << endl;
    }
  }
}

上のプログラムに適当な入力を与えると以下の出力を得る.

// test
  ignoring comment: // test
23.3 -1 3.14159
  got a number: 23.3
  got a number: -1
  got a number: 3.14159
// next batch
  ignoring comment: // next batch
1 2 3 4 5
  got a number: 1
  got a number: 2
  got a number: 3
  got a number: 4
  got a number: 5
50
  got a number: 50

getline()は現在のファイル位置から読み込みを始めるので,行の残りや指定したデリミタまでの文字列を得るのにも使える.

関連: get, getline, stringstream

 
• • • SitemapRecent changesRSScc